我想知道,删除一个包含所有文件的目录最简单的方法是什么?
我使用的是rmdir(PATH。“/”。美元价值);要删除一个文件夹,但是,如果里面有文件,我根本不能删除它。
我想知道,删除一个包含所有文件的目录最简单的方法是什么?
我使用的是rmdir(PATH。“/”。美元价值);要删除一个文件夹,但是,如果里面有文件,我根本不能删除它。
当前回答
平台独立代码。
我从PHP.net上得到了答案
if(PHP_OS === 'Windows')
{
exec("rd /s /q {$path}");
}
else
{
exec("rm -rf {$path}");
}
其他回答
现在至少有两种选择。
Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example: public static function deleteDir($dirPath) { if (! is_dir($dirPath)) { throw new InvalidArgumentException("$dirPath must be a directory"); } if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') { $dirPath .= '/'; } $files = glob($dirPath . '*', GLOB_MARK); foreach ($files as $file) { if (is_dir($file)) { self::deleteDir($file); } else { unlink($file); } } rmdir($dirPath); } And if you are using 5.2+ you can use a RecursiveIterator to do it without implementing the recursion yourself: $dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree'; $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) { if ($file->isDir()){ rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($dir);
如果你不确定,给定的路径是目录或文件,那么你可以使用这个函数删除路径
function deletePath($path) {
if(is_file($path)){
unlink($path);
} elseif(is_dir($path)){
$path = (substr($path, -1) !== DIRECTORY_SEPARATOR) ? $path . DIRECTORY_SEPARATOR : $path;
$files = glob($path . '*');
foreach ($files as $file) {
deleteDirPath($file);
}
rmdir($path);
} else {
return false;
}
}
您可以使用Symfony的文件系统(代码):
// composer require symfony/filesystem
use Symfony\Component\Filesystem\Filesystem;
(new Filesystem)->remove($dir);
但是,我不能用这个方法删除一些复杂的目录结构,所以首先您应该尝试一下,以确保它能正常工作。
我可以使用Windows特定的实现删除上述目录结构:
$dir = strtr($dir, '/', '\\');
// quotes are important, otherwise one could
// delete "foo" instead of "foo bar"
system('RMDIR /S /Q "'.$dir.'"');
为了完整起见,这里是我的一个旧代码:
function xrmdir($dir) {
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir.'/'.$item;
if (is_dir($path)) {
xrmdir($path);
} else {
unlink($path);
}
}
rmdir($dir);
}
以Linux服务器为例:exec('rm -f -r '。cache_folder美元。“/ *”);
删除一个包含所有文件的目录最简单的方法是什么?
system("rm -rf ".escapeshellarg($dir));