Monday, April 12, 2010

How to Unlink all files and folder in a particular folder?

Basically we use "unlink" to delete a file physically.
The syntax is unlink(file path including file name).

But if we want to delete all files and folder of a perticular folder then we can use this code

// arguments : The target directory , delete directory or leave it blank (true/false)
// return : none

function removeAll ($dir, $delDir) {
if(!$dh = @opendir($dir)) return;
while (false !== ($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
if (!@unlink($dir.'/'.$obj)) removeAll ($dir.'/'.$obj, true);
}
if ($delDir){
closedir($dh);
@rmdir($dir);
}
}

Note: Please change folder permission (0777) before excuting the code

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off