You can delete a directory using rmdir() function. But rmdir function has limitation. To remove a directory using rmdir , the directory must be blank. If a directory contains multiple directory and files then we have to apply recursive process.
Custom PHP function to delete folder including everything in it
Method 1
<?php
/**
* @param string $dir /path/for/the/directory/
* @return bool
**/
function delete_directory( $dir )
{
if ( is_dir( $dir ) )
{
$dir_handle = opendir( $dir );
if( $dir_handle )
{
while( $file = readdir( $dir_handle ) )
{
if($file != "." && $file != "..")
{
if( ! is_dir( $dir."/".$file ) )
{
unlink( $dir."/".$file );
}
else
{
delete_directory($dir.'/'.$file);
}
}
}
closedir( $dir_handle );
}
rmdir( $dir );
return true;
}
return false;
}
?>
Method 2
<?php
/**
* @param string $dir /path/for/the/directory/
* @return bool
**/
function delete_directory( $dir )
{
if( is_dir( $dir ) )
{
$files = glob( $dir . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
delete_directory( $file );
}
rmdir( $dir );
}
elseif( is_file( $dir ) )
{
unlink( $dir );
}
}
?>
Permalink
Hello,
I tried both of your codes but nothing happens… 🙁
My goal is to delete a folder named “test” wich is located in : wp-content/uploads/test
So that’s my code :
Any help ?
Thanks