Removing All Files From Folder in PHP

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

$AllFiles = glob('path-to-temp/*'); 
foreach($files as $file){  

Method 2

//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\\*"; 

Method 3

$cfolder = opendir($folder); 
while(false !== ($file = readdir($cfolder ))) {  
if($file != "." && $file != "..") {  
chmod($cfolder .$file, 0777);  
if(is_dir($cfolder .$file)) {  
destroy($cfolder .$file.'/');  
rmdir($cfolder .$file) or DIE("couldn't delete");  
unlink($cfolder .$file) or DIE("couldn't delete");  

Method 4

array_map('unlink', glob("path-to-dir/*"));  

Get posts by email

Like what you're reading? Get these posts delivered to your inbox.