[英]How to delete all contents of a directory without deleting the directory
我的服務器上有一個目錄,需要使用PHP清除。 我需要刪除此目錄內的所有文件和文件夾,但是,我不想刪除主目錄本身。 我讀過的所有內容,以及找到的示例,似乎都刪除了給定目錄中的所有內容,但之后也刪除了給定目錄。 我嘗試過的一個功能在下面,但是再次它也會刪除主目錄,而我卻沒有。
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
rrmdir($dir."/".$object);
else unlink ($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>
擺脫rmdir($dir);
這個rmdir($dir);
在功能的最后一部分。
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
rrmdir($dir."/".$object);
else unlink ($dir."/".$object);
}
}
reset($objects);
// rmdir($dir); => this line deletes the directory you specified after its content has been deleted
}
}
從現有代碼rmdir($ dir);中刪除此行; ,通過這一行,您還將刪除在函數參數上傳遞的父目錄。 我還添加了通常用於從目錄中刪除內容的代碼段。
function remove_directory($str) {
//It it's a file.
if (is_file($str)) {
//Attempt to delete it.
return unlink($str);
}
//If it's a directory.
elseif (is_dir($str)) {
//Get a list of the files in this directory.
$scan = glob(rtrim($str,'/').'/*');
//Loop through the list of files.
foreach($scan as $index=>$path) {
//Call our recursive function.
remove_directory($path);
}
//Remove the directory itself.
return @rmdir($str);
}
}
//call our function
$dir='directory_name';
remove_directory($dir);
我之前發布的代碼版本也刪除了子目錄,因此刪除代碼中的最后一個rmdir將阻止它執行此操作。 但是,我能夠對有效的代碼進行更改。 此代碼將刪除給定目錄內的所有內容,包括文件和文件夾,而不會刪除給定目錄。
function rrmdir($dir, $issub = false) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
rrmdir($dir."/".$object, true);
else unlink ($dir."/".$object);
}
}
reset($objects);
if($issub) {
rmdir($dir);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.