Home > Article > Backend Development > PHP deletion is not an empty directory implementation code_PHP tutorial
The built-in function rmdir in PHP can only delete empty directories. If you want to delete a directory with files or directories, you need to use it recursively with unlink. Let’s take a look at the custom function that deletes directories that are not empty.
php tutorial deleting non-empty directory implementation code
This tutorial first briefly introduces rmdir to delete empty directories, and then extends it to the writing and implementation code of custom functions that delete non-empty directories.
*/
//rmdir(dir,context) The rmdir() function deletes empty directories.
$path ='';
if( is_dir( $path ) )
{
if( rmdir( $path ) )
{
echo 'Delete directory successfully';
}
}
else
{
echo 'Not a directory';
}
/*
Summary
The function rmdir that comes with PHP can only delete empty directories. If you want to delete a directory with files or directories, you need to use it recursively with unlink. Let's take a look at the custom function that deletes directories that are not empty.
*/
/**
* Delete files or folders (recursively)
* @param array $filelist
* @param string $option
* @param string $fileext The file extension to be deleted Format: 'html'
* @return void
*/
function rm($filelist, $option='r', $fileext = null, $if_rmdir = false) {
if (!is_array($filelist)) {
$filelist = explode('|', $filelist);
}
foreach ($filelist as $filename) {
If (is_file($filename)) {
If (empty($fileext)) {
unlink($filename);
} else {
If (substr(strrchr($filename, '.'), 1 ) == $fileext){
unlink($filename);
}
}
} elseif (is_dir($filename)) {
If (strpos($option, 'r')!==false) {
$file_list_ = ls($filename);
foreach ($file_list_ as $fi => $file) {
$file_list_[$fi] = $filename . $file;
}
rm($file_list_, $option, $fileext);
}
If ($if_rmdir) {
rmdir($filename);
}
}
}
}
//Call method