[英]Delete folder and files in PHP
I have a question about the little code snippet below.我对下面的小代码片段有疑问。 At the moment I use the first code snippet and it runs perfectly.目前我使用第一个代码片段,它运行完美。 But wouldn't the second code be a better way to delete the folder and files in it?但是第二个代码不是删除文件夹和文件的更好方法吗? My variable $target
is everytime a path to the folder hwo needs to delete.我的变量$target
是每次需要删除文件夹 hwo 的路径时。
function deleteFilesAndDirectory($target)
{
if(is_dir($target))
{
$files = glob($target . '*', GLOB_MARK);
foreach($files as $file)
{
deleteFilesAndDirectory($file);
}
rmdir($target);
}
elseif(is_file($target))
{
unlink($target);
}
}
Why this code shouldn't be used?为什么不应该使用此代码?
function deleteFilesAndDirectory($target)
{
$files = glob($target . '*', GLOB_MARK);
foreach($files as $file)
{
unlink($file);
}
rmdir($target);
}
The second will work fine, so long as the directory to be deleted does not contain any subdirectories.只要要删除的目录不包含任何子目录,第二个就可以正常工作。 To clean out subdirectories, a recursive function is the best way, which is why in the first code sample the function deleteFilesAndDirectory()
calls itself.要清除子目录,递归函数是最好的方法,这就是为什么在第一个代码示例中函数deleteFilesAndDirectory()
调用自身的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.