首页 文章

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

提问于
浏览
263

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

16 回答

  • 8

    此代码来自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);
        }
    }
    
  • 1
    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);
    }
    
  • 4
    <?
    //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
    ?>
    
  • 3

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

    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."/*"));
            }
        }
    }
    
  • 9

    假设您有一个文件夹,其中包含大量文件,并且两个步骤中的删除操作都没有 . 我相信删除文件最有效的方法是使用系统命令 .

    例如在linux上我使用:

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

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

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

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

  • 79

    我更新了@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

    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);
        }
    ?>
    
  • 1

    从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/

  • 231
    $dir = 'your/directory/';
    foreach(glob($dir.'*.*') as $v){
        unlink($v);
    }
    
  • 4

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

    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');
    
  • 0
    foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
        if(!$fileInfo->isDot()) {
            unlink($fileInfo->getPathname());
        }
    }
    
  • 67
    $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);
    
  • 570

    对我来说, 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);
    }
    
  • 19

    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目录中的所有文件 .

  • 11

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

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

    Update

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

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

    这是一个使用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;
    

相关问题