Skip to content

PHP Tutorial File Handling

Working with Directories

Lesson 171 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Folders are files too, and PHP has functions to create, list and remove them.

Create a folder: mkdir()

index.php
PHP
<?php
if (!is_dir("uploads")) {
    mkdir("uploads", 0755, true);
}

var_dump(is_dir("uploads"));
Output
OUTPUT
bool(true)

The third argument true creates parent folders as needed (mkdir("a/b/c", 0755, true)). 0755 is the permission: the owner can do everything, others can read and enter. Do not use 0777 on a real server.

List the contents: scandir()

index.php
PHP
<?php
mkdir("docs");
file_put_contents("docs/a.txt", "1");
file_put_contents("docs/b.txt", "2");

print_r(scandir("docs"));
Output
OUTPUT
Array
(
    [0] => .
    [1] => ..
    [2] => a.txt
    [3] => b.txt
)

. is the folder itself and .. is its parent. You almost always want to remove them.

index.php
PHP
<?php
if (!is_dir("docs")) {
    mkdir("docs");
}
file_put_contents("docs/a.txt", "1");
file_put_contents("docs/b.txt", "2");

$files = array_values(array_diff(scandir("docs"), [".", ".."]));

echo implode(", ", $files);
Output
OUTPUT
a.txt, b.txt

Find files by pattern: glob()

index.php
PHP
<?php
mkdir("pics");
file_put_contents("pics/a.jpg", "");
file_put_contents("pics/b.png", "");
file_put_contents("pics/c.jpg", "");

foreach (glob("pics/*.jpg") as $file) {
    echo basename($file) . "\n";
}
Output
OUTPUT
a.jpg
c.jpg

glob() returns full paths that match a pattern with * and ?. It does not include . and ...

Delete an empty folder: rmdir()

index.php
PHP
<?php
mkdir("empty-folder");
rmdir("empty-folder");

var_dump(is_dir("empty-folder"));
Output
OUTPUT
bool(false)

rmdir() works only on empty folders. To remove a folder with content, delete the files first.

Walk through subfolders

RecursiveDirectoryIterator visits every file in every subfolder.

index.php
PHP
<?php
mkdir("site/css", 0755, true);
file_put_contents("site/index.html", "");
file_put_contents("site/css/style.css", "");

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator("site", FilesystemIterator::SKIP_DOTS)
);

$names = [];
foreach ($iterator as $file) {
    $names[] = str_replace("\\", "/", $file->getPathname());
}

sort($names);
echo implode("\n", $names);
Output
OUTPUT
site/css/style.css
site/index.html

The current folder

index.php
PHP
<?php
echo getcwd();   // the current working directory
echo __DIR__;    // the folder of this file

Use paths you control

A path that comes from the visitor can contain ../ to climb out of the folder you meant. Use basename() to keep only the file name, and check the result against your own list. See File Paths.

dangerous
Careful with recursive delete
A function that deletes a folder tree with a path from outside can wipe your server if the path is wrong. Never pass user input to it.