In PHP, you can use the ` unlink()` function to delete a directory. rmdir Function: This function deletes a specified directory; however, if the directory is not empty, it cannot be deleted – the files and subdirectories within it must first be removed.
Below is how to use it. rmdir Example code for deleting a specified directory using a function
$dir = '/path/to/dir'; // 要删除的目录路径
if (is_dir($dir)) { // 如果目录存在
$files = glob($dir . '/*'); // 获取目录下的所有文件和子目录
foreach ($files as $file) {
if (is_file($file)) { // 如果是文件则直接删除
unlink($file);
} else { // 如果是子目录则递归调用自身
deleteDir($file);
}
}
rmdir($dir); // 删除目录
}The above code is used. is_dir Check whether the directory exists – Use. glob The `get_all_files_and_subdirectories` function retrieves all files and subdirectories from a given directory; use it accordingly. unlink The function deletes a file using a recursive call. deleteDir Delete subdirectory; use at the end. rmdir Delete directory.
Please note that the deletion operation is irreversible; therefore, please proceed with caution.
<?php
// 定义要删除的文件夹路径
$dir = "/path/to/directory";
// 递归删除非空文件夹
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 . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
// 调用递归函数删除文件夹
if (deleteDirectory($dir)) {
echo "文件夹删除成功";
} else {
echo "文件夹删除失败";
}
?>