Working with Directories
Working with directories is the handling of the folders that hold files. A directory is a folder, and PHP can make one, list what sits inside it and remove it.
Make a folder and list it
mkdir makes the archive folder and two writes put files inside it. scandir lists the dot entries first and then the two file names in sorted order, even though b.txt was written first.
<?php
mkdir("archive");
file_put_contents("archive/b.txt", "B\n");
file_put_contents("archive/a.txt", "A\n");
print_r(scandir("archive"));glob lists only the text files
A pattern is a name shape with a star standing for any characters. The pattern here asks for names in the docs folder that end in .txt, so the .md file stays out of the list.
<?php
mkdir("docs");
file_put_contents("docs/notes.txt", "N\n");
file_put_contents("docs/list.txt", "L\n");
file_put_contents("docs/readme.md", "R\n");
print_r(glob("docs/*.txt"));Clean up a folder and its file
unlink deletes the file inside the temp folder first. rmdir then removes the empty folder, and the is_dir check prints false.
<?php
mkdir("temp");
file_put_contents("temp/junk.txt", "x");
unlink("temp/junk.txt");
rmdir("temp");
var_dump(is_dir("temp"));Example
<?php
mkdir("archive");
file_put_contents("archive/one.txt", "1\n");
file_put_contents("archive/two.txt", "2\n");
print_r(scandir("archive"));
unlink("archive/one.txt");
unlink("archive/two.txt");
rmdir("archive");
var_dump(is_dir("archive"));Key points
- mkdir makes a new folder.
- scandir lists the entries in a folder in sorted order.
- The scandir list always holds the two dot entries for the folder itself and the folder above it.
- glob returns the names that match a pattern.
- unlink deletes a file.
- rmdir removes a folder once the folder is empty.
In this example, the program builds an archive folder with two files inside it. scandir prints the sorted list with the dot entries first. The unlink calls delete both files, rmdir removes the empty folder, and the last line proves the folder is gone.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which function removes a folder once the folder is empty?