Recursive Unlinking: Understanding
Posted: Mon Jul 27, 2009 12:00 am
Hi, I've constructed a recursive unlinking function from various sources. I'm trying to comment it for understanding.
Do you see anything in my comments that I could improve on? Hopefully I built it and understood it currently...
I'm also a bit new to the opendir(), readdir(), closedir() functions. I'm guessing I want to use opendir() on the top level directory that I want to use before I call this function? Thanks!
Do you see anything in my comments that I could improve on? Hopefully I built it and understood it currently...
I'm also a bit new to the opendir(), readdir(), closedir() functions. I'm guessing I want to use opendir() on the top level directory that I want to use before I call this function? Thanks!
Code: Select all
<?php
// inspired by:
// http://us2.php.net/manual/en/function.unlink.php#87045
// viewtopic.php?f=1&t=25543&hilit=recursive+unlink
// delete all files, directories within given directory.
// even deletes given top-level directory ($dir).
function recursive_unlink($dir)
{
// base case: if the given directory isn't the top-level directory, do nothing
if(!$dir_handle = opendir($dir))
{
return;
}
// otherwise, go through contents of top-level directory
while(($file = readdir($dir_handle)) !== false)
{
// skip the folder if it's empty
if($file == '.' || $file == '..')
{
continue;
}
// if there's anything in the folder, kill it
if (!unlink($dir.'/'.$file))
{
recursive_unlink($dir.'/'.$file);
}
}
closedir($dir_handle); // close the top-level directory
rmdir($dir); // remove the top-level directory
return;
}
?>