I am in need to delete a folder with contents using PHP. rmdir( ) and unlink( ) are deleting the folder which is empty. But not able to delete the folders which contain contents.
could anyone help me regarding this issue.
thanks in Advance...
Fero
I am in need to delete a folder with contents using PHP. rmdir( ) and unlink( ) are deleting the folder which is empty. But not able to delete the folders which contain contents.
could anyone help me regarding this issue.
thanks in Advance...
Fero
You need to loop around the folder contents (including the contents of any subfolders) and remove them first.
There's an example here: http://lixlpixel.org/recursive%5Ffunction/php/recursive%5Fdirectory%5Fdelete/
Be careful with it!!!
You will have to delete all the files recursively. There are plenty example functions in the comments of the rmdir manual page:
There are some useful libraries for recursive deletion of directories here.
This function will allow you to delete any folder (as long as it's writable) and it's files and subdirectories.
function Delete($path)
{
if (is_dir($path) === true)
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
There is no single function build into PHP that would allow this, you have to write your own with rmdir and unlink.
An example (taken from a comment on php.net docs):
<?
// ensure $dir ends with a slash
function delTree($dir) {
$files = glob( $dir . '*', GLOB_MARK );
foreach( $files as $file ){
if( substr( $file, -1 ) == '/' )
delTree( $file );
else
unlink( $file );
}
rmdir( $dir );
}
?>
Here's a script that will do just what you need:
/**
* Recursively delete a directory
*
* @param string $dir Directory name
* @param boolean $deleteRootToo Delete specified top-level directory as well
*/
function unlinkRecursive($dir, $deleteRootToo)
{
if(!$dh = @opendir($dir))
{
return;
}
while (false !== ($obj = readdir($dh)))
{
if($obj == '.' || $obj == '..')
{
continue;
}
if (!@unlink($dir . '/' . $obj))
{
unlinkRecursive($dir.'/'.$obj, true);
}
}
closedir($dh);
if ($deleteRootToo)
{
@rmdir($dir);
}
return;
}
I got it from php.net and it works.
Perhaps a better approach is to use rm (if you're under linux). It would go something like this ($root should ALWAYS be set to your TMP directory to prevent deleting vital files!):
function remove($dir) {
$root = $_SERVER['DOCUMENT_ROOT'].'/tmp/';
if (is_dir($root.$dir)) {
exec('rm -rf '.$root.$dir);
}
}