Deleting all files from a folder using PHP?

getaway picture getaway · Jan 4, 2011 · Viewed 347.7k times · Source

For example I had a folder called `Temp' and I wanted to delete or flush all files from this folder using PHP. Could I do this?

Answer

Floern picture Floern · Jan 4, 2011
$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file)) {
    unlink($file); // delete file
  }
}

If you want to remove 'hidden' files like .htaccess, you have to use

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);