Search code examples
phpexitunlink

how to delete all files with php in a folder when you use an exit after the unlink


I am using this code to delete all files in a folder and it works fine:

if(isset($_POST['deleteall'])) {

    $files = glob($dir.'/*'); // get all file names
    foreach($files as $file){ // iterate files
        if(is_file($file)) {
          unlink($file); // delete files                               
        }   
    }     
exit;
}

When i put the exit straight after the unlink, like below, it does not work anymore.

if(isset($_POST['deleteall'])) {

    $files = glob($dir.'/*'); // get all file names
    foreach($files as $file){ // iterate files
       if(is_file($file)) {
       unlink($file); // delete files
       exit;                               
       }   
    }     

}

Can someone explain me why the exit must be placed out of the foreach loop? Because after the unlink, everything is deleted and you can place an exit, but unfortunately....


Solution

  • Your assumption of

    unlink($file); // delete files
    //                ************
    

    is incorrect. This is deleting 1 file at a time You need to let the foreach finish so that every file in the directory is deleted.