Wednesday, September 12, 2012

How to delete all the files from the directory in PHP

<?PHP

emptyDir("/home/DIR_NAME/public_html");

FUNCTION emptyDir($path) {

// init the debug string
$debugStr = '';
$debugStr .= "DeletingContents Of: $path<br /><br />";

// parse the folder
IF ($handle = OPENDIR($path)) {

WHILE (FALSE !== ($file = READDIR($handle))) {

IF ($file != "." && $file != "..") {

// If it's a file, delete it
IF(IS_FILE($path."/".$file)) {

IF(UNLINK($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}

} ELSE {

// It's a directory...
// crawl through the directory and delete the
contents
IF($handle2 = OPENDIR($path."/".$file)) {

WHILE (FALSE !== ($file2 = READDIR($handle2))) {

IF ($file2 != "." && $file2 != "..") {
IF(UNLINK($path."/".$file."/".$file2)) {
$debugStr .= "Deleted File:
$file/$file2<br />";
}
}

}

}

IF(RMDIR($path."/".$file)) {
$debugStr .= "Directory: ".$file."<br />";
}

}

}

}

}
RETURN $debugStr;
}

0 comments:

Post a Comment