Advertisement
Intermediate PHP, File Handling & File System Functions

How do you work with directories in PHP, including listing their contents, creating new directories, and recursively deleting them?

Short answer

The scandir function returns an array of all files and subdirectories within a given directory, mkdir creates a new directory including the option to create nested parent directories at once, and safely deleting a directory recursively typically requires writing a custom…

Save PHP mock interview
Advertisement
AModel answer
The scandir function returns an array of all files and subdirectories within a given directory, mkdir creates a new directory including the option to create nested parent directories at once, and safely deleting a directory recursively typically requires writing a custom function that first deletes all of its contents before finally removing the now empty directory itself, since PHP's built in rmdir function only works on already empty directories.
mkdir('uploads/2026', recursive: true);
$files = scandir('uploads/2026');
foreach ($files as $file) {
    if ($file !== '.' && $file !== '..') {
        echo $file . PHP_EOL;
    }
}
Real-world example
A file upload system organizes uploaded files into dated subdirectories, using mkdir with the recursive option to automatically create the full nested directory structure for the current year and month if it does not already exist.
Likely follow-ups
  • Why does scandir always include the current directory and parent directory entries?
  • What library functions simplify recursive directory operations compared to writing your own custom recursive function?
Related topics