HomePHP Page 10 - File And Directory Manipulation In PHP (part 2)
Purging The Dead - PHP
Now that you know the basics of reading and writing files, this second segment of our tutorial on the PHP filesystem API takes you into deeper waters, showing you how to copy, delete and rename files; scan directories; work with uploaded files over HTTP; perform pattern matches on file names; and read and write to processes instead of files.
Not only does PHP let you read directory contents, it also allows you to create and delete directories with the mkdir() and rmdir() functions respectively. Consider the following example, which creates a directory,
<?php
// create directory
mkdir("/tmp/stuff") or die ("Could not make directory");
?>
and its mirror image, which removes the newly-created directory.
<?php
// erase directory
rmdir("/tmp/stuff") or die ("Could not erase directory");
?>
As with the other filesystem manipulation functions, these functions too will fail if the user the Web server is running as lacks sufficient privileges to create and delete directories on the disk. Directories created with mkdir() will be owned by the process running the Web server.
It's interesting also to note that the rmdir() function operates only if the directory to be deleted is completely empty. Try running it on a directory containing existing files, as below,
<?php
// create directory
mkdir("/tmp/stuff") or die ("Could not make directory");
// create sub-directory
mkdir("/tmp/stuff/personal") or die ("Could not make directory");
// remove parent directory
rmdir("/tmp/stuff") or die ("Could not remove directory");
?>
and you'll be rewarded with the following error:
Warning: mkdir(): File exists in /home/web/rmdir.php on line 4 Could not remove directory
Since it's unlikely that you'll find empty directories just waiting for your rmdir() in the real world, you'll normally need to empty the directory manually prior to calling rmdir() on it. The following example demonstrates, by combining the unlink() function discussed previously with some recursive logic to create a function designed specifically to erase the contents of a directory (and its sub-directories) in one fell swoop:
<?php
// recurses into a directory and empties it
// call it like this: purge("/dir/")
// remember the trailing slash!
function purge($dir)
{
$handle = opendir($dir);
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
if (is_dir($dir.$file))
{
purge ($dir.$file."/");
rmdir($dir.$file);
}
else
{
unlink($dir.$file);
}
}
}
closedir($handle);
}