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

get*_*way 289 php directory glob file

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

Flo*_*ern 607

$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file))
    unlink($file); // delete file
}
Run Code Online (Sandbox Code Playgroud)

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

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);
Run Code Online (Sandbox Code Playgroud)

  • 虽然很明显,但我会提到,例如,'path/to/temp/*.txt'将只删除txt文件,依此类推. (5认同)
  • 还有DirectoryIterator或DirectoryRecursiveIterator. (4认同)

Sti*_*oza 253

如果你想删除一切从文件夹(包括子文件夹)使用这个组合array_map,unlink以及glob:

array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );
Run Code Online (Sandbox Code Playgroud)

更新

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

array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );
Run Code Online (Sandbox Code Playgroud)

  • 最好的答案,谢谢.为了避免注意,我也会做`glob("...")?:[]`(PHP 5.4+)因为对于一个空目录`glob()`返回`false`. (31认同)
  • 它删除当前文件夹中的所有文件,但它会返回子文件夹的警告,但不会删除它们. (13认同)
  • @Ewout:即使我们将Stichoza和Moujuba的答案结合起来,因为你的给出了对子文件夹的相同警告并且它不会删除它们 (7认同)
  • 不幸的是,这不会删除子文件夹. (3认同)
  • 结合Stichoza和mojuba的答案:`array_map('unlink',(glob("path/to/temp/*")?glob("path/to/temp/*"):array()));` (2认同)
  • 要“抑制”错误警告,请使用 `@array_map('unlink', glob("path/to/temp/*"));` (2认同)

Yam*_*iko 87

这是使用标准PHP库(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;
Run Code Online (Sandbox Code Playgroud)

  • 这很好用,当您没有 SSH 访问权限并且 FTP 需要花费 **小时** 递归删除大量文件和文件夹......我在不到 3 秒的时间内删除了 35000 个文件! (3认同)
  • 对于 PHP 7.1 用户:必须使用 $file->getRealPath() 而不是 $file。否则,PHP 将给出错误消息,指出取消链接需要路径,而不是 SplFileInfo 的实例。 (3认同)

Jak*_*ris 68

foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你甚至可以取消链接($ fileInfo-> getPathname()); 这将为您提供文件的完整路径.http://php.net/manual/en/directoryiterator.getpathname.php (8认同)
  • “DirectoryIterator”不是也迭代子目录吗?如果是这样,“取消链接”将在这种情况下生成警告。循环体不应该看起来更像Yamiko的答案吗,并在调用“unlink”之前检查每个条目是否是一个文件? (2认同)

Poe*_*rin 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Hai*_*vgi 14

$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}
Run Code Online (Sandbox Code Playgroud)


Sta*_*eXV 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);
    }
?>
Run Code Online (Sandbox Code Playgroud)


Dar*_*rno 9

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

例如在linux上我使用:

exec('rm -f '. $absolutePathToFolder .'*');
Run Code Online (Sandbox Code Playgroud)

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

exec('rm -f -r '. $absolutePathToFolder .'*');
Run Code Online (Sandbox Code Playgroud)

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

  • 如果`$ absolutePatToFolder`是空的,使用这种方法有点不安全 (2认同)
  • @LawrenceCherone我希望现在没有人用root权限运行php.认真对待,我希望输入是"安全的",就像所有上述功能一样. (2认同)
  • 可能想使用 /* 只是为了确定:-) (2认同)

小智 8

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

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

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


Tof*_*eeq 5

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); 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

//get current working directory
$dir = getcwd();
unlinkr($dir);
Run Code Online (Sandbox Code Playgroud)

如果您只想删除 php 文件,请按如下方式调用它

unlinkr($dir, "*.php");
Run Code Online (Sandbox Code Playgroud)

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

unlinkr("/home/user/temp");
Run Code Online (Sandbox Code Playgroud)

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