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

时间:2021-02-17 16:02:09

For example I had a folder called `Temp' and I wanted to delete or flush all files from this folder using PHP. Could I do this?

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

15 个解决方案

#1


540  

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

If you want to remove 'hidden' files like .htaccess, you have to use

如果想要删除.htaccess等“隐藏”文件,就必须使用

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

#2


216  

If you want to delete everything from folder (including subfolders) use this combination of array_map, unlink and glob:

如果您想从文件夹(包括子文件夹)删除所有内容,请使用array_map、unlink和glob的组合:

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

#3


70  

Here is a more modern approach using the Standard PHP Library (SPL).

这里有一种使用标准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;

#4


65  

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

#5


19  

This code from http://php.net/unlink:

这段代码从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);
    }
}

#6


13  

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

#7


10  

See readdir and unlink.

看到readdir和分离。

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

#8


8  

Assuming you have a folder with A LOT of files reading them all and then deleting in two steps is not that performing. I believe the most performing way to delete files is to just use a system command.

假设您有一个文件夹,其中有很多文件都在读取它们,然后用两个步骤删除它们,那么执行起来就不是很好。我认为最有效的删除文件的方法就是使用系统命令。

For example on linux I use :

例如我使用的linux:

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

Or this if you want recursive deletion without the need to write a recursive function

或者,如果您希望递归删除,而不需要编写递归函数,那么可以这样做

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

the same exact commands exists for any OS supported by PHP. Keep in mind this is a PERFORMING way of deleting files. $absolutePathToFolder MUST be checked and secured before running this code and permissions must be granted.

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

#9


7  

The simple and best way to delete all files from a folder in PHP

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

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

Got this source code from here - http://www.codexworld.com/delete-all-files-from-folder-using-php/

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

#10


4  

Another solution: This Class delete all files, subdirectories and files in the sub directories.

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

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

#11


4  

unlinkr function recursively deletes all the folders and files in given path by making sure it doesn't delete the script itself.

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

if you want to delete all files and folders where you place this script then call it as following

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

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

if you want to just delete just php files then call it as following

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

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

you can use any other path to delete the files as well

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

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

This will delete all files in home/user/temp directory.

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

#12


3  

Posted a general purpose file and folder handling class for copy, move, delete, calculate size, etc., that can handle a single file or a set of folders.

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

https://gist.github.com/4689551

https://gist.github.com/4689551

To use:

使用方法:

To copy (or move) a single file or a set of folders/files:

复制(或移动)单个文件或一组文件夹/文件:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

Delete a single file or all files and folders in a path:

在路径中删除单个文件或所有文件和文件夹:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

Calculate the size of a single file or a set of files in a set of folders:

计算单个文件或一组文件夹中的一组文件的大小:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');

#13


1  

For me, the solution with readdir was best and worked like a charm. With glob, the function was failing with some scenarios.

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

#14


0  

I updated the answer of @Stichoza to remove files through subfolders.

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

#15


0  

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


540  

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

If you want to remove 'hidden' files like .htaccess, you have to use

如果想要删除.htaccess等“隐藏”文件,就必须使用

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

#2


216  

If you want to delete everything from folder (including subfolders) use this combination of array_map, unlink and glob:

如果您想从文件夹(包括子文件夹)删除所有内容,请使用array_map、unlink和glob的组合:

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

#3


70  

Here is a more modern approach using the Standard PHP Library (SPL).

这里有一种使用标准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;

#4


65  

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

#5


19  

This code from http://php.net/unlink:

这段代码从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);
    }
}

#6


13  

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

#7


10  

See readdir and unlink.

看到readdir和分离。

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

#8


8  

Assuming you have a folder with A LOT of files reading them all and then deleting in two steps is not that performing. I believe the most performing way to delete files is to just use a system command.

假设您有一个文件夹,其中有很多文件都在读取它们,然后用两个步骤删除它们,那么执行起来就不是很好。我认为最有效的删除文件的方法就是使用系统命令。

For example on linux I use :

例如我使用的linux:

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

Or this if you want recursive deletion without the need to write a recursive function

或者,如果您希望递归删除,而不需要编写递归函数,那么可以这样做

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

the same exact commands exists for any OS supported by PHP. Keep in mind this is a PERFORMING way of deleting files. $absolutePathToFolder MUST be checked and secured before running this code and permissions must be granted.

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

#9


7  

The simple and best way to delete all files from a folder in PHP

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

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

Got this source code from here - http://www.codexworld.com/delete-all-files-from-folder-using-php/

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

#10


4  

Another solution: This Class delete all files, subdirectories and files in the sub directories.

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

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

#11


4  

unlinkr function recursively deletes all the folders and files in given path by making sure it doesn't delete the script itself.

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

if you want to delete all files and folders where you place this script then call it as following

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

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

if you want to just delete just php files then call it as following

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

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

you can use any other path to delete the files as well

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

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

This will delete all files in home/user/temp directory.

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

#12


3  

Posted a general purpose file and folder handling class for copy, move, delete, calculate size, etc., that can handle a single file or a set of folders.

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

https://gist.github.com/4689551

https://gist.github.com/4689551

To use:

使用方法:

To copy (or move) a single file or a set of folders/files:

复制(或移动)单个文件或一组文件夹/文件:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

Delete a single file or all files and folders in a path:

在路径中删除单个文件或所有文件和文件夹:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

Calculate the size of a single file or a set of files in a set of folders:

计算单个文件或一组文件夹中的一组文件的大小:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');

#13


1  

For me, the solution with readdir was best and worked like a charm. With glob, the function was failing with some scenarios.

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

#14


0  

I updated the answer of @Stichoza to remove files through subfolders.

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

#15


0  

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