Delete Directory in PHP

This post will be helpful to those who work with directories and files.

I am writing here the PHP code for deleting the directory.

<?php

$extract_dir = 'path'; //physical path of the directory

if(deleteDirectory($extract_dir)) //delete directory
{
	$msg = "$extract_dir was deleted";
	echo $msg."<br/>";
}
else
{
	$msg = "$extract_dir was not deleted";
	echo $msg."<br/>";
}

//delete directory and files inside it
//start
function deleteDirectory($dir)
{
        if (!file_exists($dir)) return true;
        if (!is_dir($dir)) return unlink($dir);
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!deleteDirectory($dir.DS.$item)) return false;
        }
        return rmdir($dir);
}
//end

?>

Leave a Reply

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

Scroll to top