简体   繁体   中英

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

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().

You can get all directory contents with glob and check if the value is a file with is_file() before unlinking it.

$files = glob('files/*'); // get directory contents
foreach ($files as $file) { // iterate files      
   // Check if file
   if (is_file($file)) {
      unlink($file); // delete file
   }
}

If you want to remove files matching a pattern like .png or .jpg, you have to use

$files = glob('/tmp/*.{png,jpg}', GLOB_BRACE);

See manual for glob .

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