Removing All Files From Folder in PHP
Published on May 19, 2013
This is a very simple trick i want to share. For example you have a folder Temp and you don’t want it to be filled with all unnecessary files in your php app you can use any of the following code to remove all files from folder.
Method 1
<?php
$AllFiles = glob('path-to-temp/*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
?>
Method 2
<?php
//Detecting OS php running executing command to remove
$os = strtolower(php_uname());
$cmd = "rm -r path-to-temp/*";
if (strpos($os, "darwin") !== false) {
$cmd="rm -rf path-to-temp/*";
} else if (strpos($os, "win") !== false) {
$cmd = "del /Q c:\\Path-to-dir\\*";
}
system($co);
?>
Method 3
<?php
$folder="path-to-dir";
$cfolder = opendir($folder);
while(false !== ($file = readdir($cfolder ))) {
if($file != "." && $file != "..") {
chmod($cfolder .$file, 0777);
if(is_dir($cfolder .$file)) {
chdir('.');
destroy($cfolder .$file.'/');
rmdir($cfolder .$file) or DIE("couldn't delete");
}
else
unlink($cfolder .$file) or DIE("couldn't delete");
}
}
closedir($cfolder);
?>
Method 4
<?php
array_map('unlink', glob("path-to-dir/*"));
?>