简体   繁体   中英

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);
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM