Folders are files too, and PHP has functions to create, list and remove them.
Create a folder: mkdir()
<?php
if (!is_dir("uploads")) {
mkdir("uploads", 0755, true);
}
var_dump(is_dir("uploads"));
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()
<?php
mkdir("docs");
file_put_contents("docs/a.txt", "1");
file_put_contents("docs/b.txt", "2");
print_r(scandir("docs"));
Array
(
[0] => .
[1] => ..
[2] => a.txt
[3] => b.txt
)
. is the folder itself and .. is its parent. You almost always want to remove them.
<?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);
a.txt, b.txt
Find files by pattern: glob()
<?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";
}
a.jpg
c.jpg
glob() returns full paths that match a pattern with * and ?. It does not include . and ...
Delete an empty folder: rmdir()
<?php
mkdir("empty-folder");
rmdir("empty-folder");
var_dump(is_dir("empty-folder"));
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.
<?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);
site/css/style.css
site/index.html
The current folder
<?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.