繁体   English   中英

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

[英]Deleting all files from a folder using PHP?

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

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

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

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

此调用还可以处理空目录(感谢您的提示,@mojuba!)

这是使用标准 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;
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

此代码来自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);
    }
}
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}

假设你有一个文件夹,里面有很多文件,读取它们,然后分两步删除,效果并不好。 我相信删除文件最有效的方法是使用系统命令。

例如在 linux 上我使用:

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

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

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

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

请参阅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);
    }
?>

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

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

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

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

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

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');
 <?
//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);
}
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);
}

我已经构建了一个非常简单的包,称为“Pusheh”。 使用它,您可以清除目录或完全删除目录( Github 链接)。 它也可以在Packagist找到

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

Pusheh::clearDir("Temp");

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

如果您有兴趣,请参阅wiki

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

这是一个简单的方法和很好的解决方案。 试试这个代码。

array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM