使用PHP删除文件夹中的所有文件?

问题描述 投票:272回答:17

例如,我有一个名为`Temp'的文件夹,我想使用PHP删除或刷新此文件夹中的所有文件。我可以这样做吗?

php file directory folder
17个回答
583
投票
$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file))
    unlink($file); // delete file
}

如果你想删除像'.htaccess这样的'隐藏'文件,你必须使用

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);

4
投票

另一种解决方案:此类删除子目录中的所有文件,子目录和文件。

class Your_Class_Name {
    /**
     * @see http://php.net/manual/de/function.array-map.php
     * @see http://www.php.net/manual/en/function.rmdir.php 
     * @see http://www.php.net/manual/en/function.glob.php
     * @see http://php.net/manual/de/function.unlink.php
     * @param string $path
     */
    public function delete($path) {
        if (is_dir($path)) {
            array_map(function($value) {
                $this->delete($value);
                rmdir($value);
            },glob($path . '/*', GLOB_ONLYDIR));
            array_map('unlink', glob($path."/*"));
        }
    }
}

4
投票

unlinkr函数通过确保它不删除脚本本身来递归删除给定路径中的所有文件夹和文件。

function unlinkr($dir, $pattern = "*") {
    // find all files and folders matching pattern
    $files = glob($dir . "/$pattern"); 

    //interate thorugh the files and folders
    foreach($files as $file){ 
    //if it is a directory then re-call unlinkr function to delete files inside this directory     
        if (is_dir($file) and !in_array($file, array('..', '.')))  {
            echo "<p>opening directory $file </p>";
            unlinkr($file, $pattern);
            //remove the directory itself
            echo "<p> deleting directory $file </p>";
            rmdir($file);
        } else if(is_file($file) and ($file != __FILE__)) {
            // make sure you don't delete the current script
            echo "<p>deleting file $file </p>";
            unlink($file); 
        }
    }
}

如果要删除放置此脚本的所有文件和文件夹,请按以下方式调用它

//get current working directory
$dir = getcwd();
unlinkr($dir);

如果你只想删除只是php文件,然后调用它如下

unlinkr($dir, "*.php");

您也可以使用任何其他路径删除文件

unlinkr("/home/user/temp");

这将删除home / user / temp目录中的所有文件。


3
投票

发布了一个通用文件和文件夹处理类,用于复制,移动,删除,计算大小等,可以处理单个文件或一组文件夹。

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');

1
投票
 <?
//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
?> 

1
投票

对我而言,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);
}

0
投票

我更新了@Stichoza的答案,通过子文件夹删除文件。

function glob_recursive($pattern, $flags = 0) {
    $fileList = glob($pattern, $flags);
    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $subPattern = $dir.'/'.basename($pattern);
        $subFileList = glob_recursive($subPattern, $flags);
        $fileList = array_merge($fileList, $subFileList);
    }
    return $fileList;
}

function glob_recursive_unlink($pattern, $flags = 0) {
    array_map('unlink', glob_recursive($pattern, $flags));
}

0
投票
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);
}

0
投票

有一个名为“Pusheh”的包裹。使用它,您可以清除目录或完全删除目录(Github link)。它也可以在Packagist上找到。

例如,如果要清除Temp目录,可以执行以下操作:

Pusheh::clearDir("Temp");

// Or you can remove the directory completely
Pusheh::removeDirRecursively("Temp");

如果您有兴趣,请参阅the wiki


243
投票

如果要删除文件夹(包括子文件夹)中的所有内容,请使用array_mapunlinkglob的组合:

array_map('unlink', glob("path/to/temp/*"));

更新

这个调用也可以处理空目录 - 感谢提示,@ mojuba!

array_map('unlink', array_filter((array) glob("path/to/temp/*")));

84
投票

这是使用Standard PHP Library (SPL)的更现代的方法。

$dir = "path/to/directory";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}
return true;

68
投票
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

19
投票

来自http://php.net/unlink的代码:

/**
 * Delete a file or recursively delete a directory
 *
 * @param string $str Path to file or directory
 */
function recursiveDelete($str) {
    if (is_file($str)) {
        return @unlink($str);
    }
    elseif (is_dir($str)) {
        $scan = glob(rtrim($str,'/').'/*');
        foreach($scan as $index=>$path) {
            recursiveDelete($path);
        }
        return @rmdir($str);
    }
}

14
投票
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}

11
投票

readdirunlink

<?php
    if ($handle = opendir('/path/to/files'))
    {
        echo "Directory handle: $handle\n";
        echo "Files:\n";

        while (false !== ($file = readdir($handle)))
        {
            if( is_file($file) )
            {
                unlink($file);
            }
        }
        closedir($handle);
    }
?>

9
投票

假设你有一个文件夹,其中包含大量文件,然后以两个步骤删除,那就不是这样了。我相信删除文件最有效的方法是使用系统命令。

例如在linux上我使用:

exec('rm -f '. $absolutePathToFolder .'*');

或者如果你想要递归删除而不需要编写递归函数

exec('rm -f -r '. $absolutePathToFolder .'*');

PHP支持的任何操作系统都存在相同的命令。请记住,这是一种删除文件的执行方式。在运行此代码之前,必须检查并保护$ absolutePathToFolder,并且必须授予权限。


8
投票

从PHP中删除文件夹中所有文件的简单而最好的方法

$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
    if(is_file($file))
    unlink($file); //delete file
}

从这里得到这个源代码 - http://www.codexworld.com/delete-all-files-from-folder-using-php/

© www.soinside.com 2019 - 2024. All rights reserved.