Delete Entire Folder with PHP Code

Today, I had to write a block of pure PHP code to delete an entire folder full of files, sub-folders and more files from a server. This particular job was for a WordPress plugin, but the code I used is not specific to WordPress and can run just fine outside of WordPress or inside a WordPress plugin. The only requirement is an up to date PHP installation for this code to function as intended.


$path = ABSPATH.’wp-content/plugins/cultivate-crm/test’;
$dir_arr = parse_dir($path);
global $darr;

function parse_dir($path){
static $cntf = 0;
global $darr;
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = “{$path}/{$entry}”;
//Check whether the entry is a file or folder.:
$fof = $entry;
    if($fof != “.” && $fof != “..”) {
    $fof = $entry;
    $file_type = filetype($filepath);//get file type.
    $file_size = filesize($filepath);//get file size.
    echo “$cntf) $fof<br />Type: $file_type<br />Size: $file_size<hr />”;
    if($file_type==’dir’){$darr[]=$filepath;parse_dir($filepath);}else{echo “Deleting $filepath….<br>”;unlink($filepath);}
    }//end if is file etc.
}//end while going over files in excel_uploads dir.
}//end parse_dir PHP function by Ian L. of

$c = count($darr);
echo “$c empty directories remain…deleting them now….<br />”;
$rdarr = array_reverse($darr);
foreach($rdarr as $dr){
    echo “Folder $dr deleted!<br />”;
//and finally remove the test folder:
$test_folder = ABSPATH.’wp-content/plugins/cultivate-crm/test’;
echo “Folder $test_folder deleted!<br /><p style=’color:green’>Now all temporary folders have been removed from the server!</p>”;

Make sure you set your path variable at the top of the script correctly and if you are not in WordPress, replace ABSPATH or set a new PHP constant named ABSPATH and it will work as it is. Since the above code deals with deleting files permanently from the server, I must insist that you use it at your own risk! Be careful because one wrong path entered into this function can destroy your entire file system if you don’t know what you are doing!

Leave a Reply

Your email address will not be published. Required fields are marked *