例如,我有一个名为“Temp”的文件夹,我想使用PHP删除或刷新该文件夹中的所有文件。我可以这样做吗?
当前回答
这是一个简单的方法和很好的解决方案。试试这段代码。
array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));
其他回答
public static function recursiveDelete($dir)
{
foreach (new \DirectoryIterator($dir) as $fileInfo) {
if (!$fileInfo->isDot()) {
if ($fileInfo->isDir()) {
recursiveDelete($fileInfo->getPathname());
} else {
unlink($fileInfo->getPathname());
}
}
}
rmdir($dir);
}
<?
//delete all files from folder & sub folders
function listFolderFiles($dir)
{
$ffs = scandir($dir);
echo '<ol>';
foreach ($ffs as $ff) {
if ($ff != '.' && $ff != '..') {
if (file_exists("$dir/$ff")) {
unlink("$dir/$ff");
}
echo '<li>' . $ff;
if (is_dir($dir . '/' . $ff)) {
listFolderFiles($dir . '/' . $ff);
}
echo '</li>';
}
}
echo '</ol>';
}
$arr = array(
"folder1",
"folder2"
);
for ($x = 0; $x < count($arr); $x++) {
$mm = $arr[$x];
listFolderFiles($mm);
}
//end
?>
对我来说,使用readdir的解决方案是最好的,而且非常有效。对于glob,该函数在某些情况下会失败。
// Remove a directory recursively
function removeDirectory($dirPath) {
if (! is_dir($dirPath)) {
return false;
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
if ($handle = opendir($dirPath)) {
while (false !== ($sub = readdir($handle))) {
if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
$file = $dirPath . $sub;
if (is_dir($file)) {
removeDirectory($file);
} else {
unlink($file);
}
}
}
closedir($handle);
}
rmdir($dirPath);
}
发布了一个通用的文件和文件夹处理类,用于复制,移动,删除,计算大小等,可以处理单个文件或一组文件夹。
https://gist.github.com/4689551
使用方法:
复制(或移动)一个文件或一组文件夹/文件:
$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');
删除单个文件或删除路径下的所有文件和文件夹:
$files = new Files();
$results = $files->delete('source/folder/optional-file.name');
计算单个文件或一组文件夹中文件的大小:
$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}