Search code examples
phpfileunlink

How to delete file in PHP


I want to delete files in a specific directory in PHP. How can I achieve this? I have the following code but it does not delete the files.

$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
    if ($file != '.' && $file != '..') {
        $files[] = $file;
    }
    unlink($file);
} 

Solution

  • I think your question isn't specific, this code must clear all files in the directory 'files'.

    But there are some errors in that code I think, and here is the right code:

            $files= array();
            $dir = dir('files');
            while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
               if ($file != '.' && $file != '..') {
                  $files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..) 
               }
               unlink('files/'.$file); // This must remove the file in the queue 
            } 
    

    And finally make sure that you provided the right path to dir().