Folders and paths
A program works not only with single files but with folders too: it creates them for uploaded pictures, goes through files, builds paths. PHP has a separate set of functions for that.
Creating a folder
mkdir() creates a folder. The third argument true allows creating a whole chain of nested folders at once:
<?php
$dir = sys_get_temp_dir() . '/shop/images';
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
var_dump(is_dir($dir)); // bool(true)The is_dir() check is needed because creating a folder that already exists raises a warning.
Listing files
scandir() returns the names of everything in a folder. Among them are the service entries . and .. — they are removed:
<?php
$dir = sys_get_temp_dir() . '/notes-demo';
if (!is_dir($dir)) {
mkdir($dir);
}
file_put_contents($dir . '/a.txt', 'A');
file_put_contents($dir . '/b.txt', 'B');
$files = array_diff(scandir($dir), ['.', '..']);
echo implode(', ', $files); // a.txt, b.txtSearching by a mask
glob() finds files by a name pattern and returns full paths:
<?php
$dir = sys_get_temp_dir() . '/glob-demo';
if (!is_dir($dir)) {
mkdir($dir);
}
file_put_contents($dir . '/photo.jpg', '');
file_put_contents($dir . '/notes.txt', '');
$images = glob($dir . '/*.jpg');
echo count($images), ' ', basename($images[0]); // 1 photo.jpgThe asterisk stands for any number of characters.
Parts of a path
<?php
$path = '/var/www/site/uploads/photo.final.jpg';
echo basename($path), "\n"; // photo.final.jpg
echo dirname($path), "\n"; // /var/www/site/uploads
echo pathinfo($path, PATHINFO_EXTENSION), "\n"; // jpg
echo pathinfo($path, PATHINFO_FILENAME); // photo.finalThese functions work on the string — the file itself need not exist.
A path from the current file
A relative path depends on the folder the program was started from. The __DIR__ constant always holds the folder of the current file, so a path built from it is reliable:
<?php
$config = __DIR__ . '/config/app.php';
echo basename($config); // app.phpFile information
<?php
$file = sys_get_temp_dir() . '/info-demo.txt';
file_put_contents($file, 'Hello!');
echo filesize($file), "\n"; // 6
var_dump(is_file($file)); // bool(true)
echo date('Y', filemtime($file)) >= 2025 ? 'changed recently' : 'old';filesize() returns the size in bytes. filemtime() is the time of the last change.
Deleting
unlink() deletes a file, rmdir() deletes an empty folder:
<?php
$dir = sys_get_temp_dir() . '/remove-demo';
if (!is_dir($dir)) {
mkdir($dir);
}
file_put_contents($dir . '/temp.txt', '');
unlink($dir . '/temp.txt');
rmdir($dir);
var_dump(is_dir($dir)); // bool(false)Common mistake
rmdir() does not delete a folder that has something in it. Everything inside has to be deleted first. And never put user input into a path as is: the string ../../config.php leads outside the allowed folder. Keep only the last part of the name:
<?php
$requested = '../../secret/config.php';
echo basename($requested); // config.php