tobias s tobias s - 3 months ago 21
PHP Question

Delete folder and files in PHP

I have a question about the little code snippet below.
At the moment I use the first code snippet and it runs perfectly.
But wouldn't the second code be a better way to delete the folder and files in it?
My variable

$target
is everytime a path to the folder hwo needs to delete.

function deleteFilesAndDirectory($target)
{
if(is_dir($target))
{
$files = glob($target . '*', GLOB_MARK);
foreach($files as $file)
{
deleteFilesAndDirectory($file);
}
rmdir($target);
}
elseif(is_file($target))
{
unlink($target);
}
}


Why this code shouldn't be used?

function deleteFilesAndDirectory($target)
{
$files = glob($target . '*', GLOB_MARK);
foreach($files as $file)
{
unlink($file);
}
rmdir($target);
}

Answer

The second will work fine, so long as the directory to be deleted does not contain any subdirectories. To clean out subdirectories, a recursive function is the best way, which is why in the first code sample the function deleteFilesAndDirectory() calls itself.

Comments