PHP:取消链接目录中的所有文件,然后删除该目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11267086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:08:27  来源:igfitidea点击:

PHP: Unlink All Files Within A Directory, and then Deleting That Directory

phpunlinkrmdir

提问by NoodleOfDeath

I there a way I can use RegExp or Wildcard searches to quickly delete all files within a folder, and then remove that folder in PHP, WITHOUT using the "exec" command? My server does not give me authorization to use that command. A simple loop of some kind would suffice.

我有一种方法可以使用 RegExp 或通配符搜索快速删除文件夹中的所有文件,然后在 PHP 中删除该文件夹,而无需使用“exec”命令?我的服务器没有授权我使用该命令。某种简单的循环就足够了。

I need something that would accomplish the logic behind the following statement, but obviously, would be valid:

我需要一些可以完成以下语句背后的逻辑的东西,但显然,这将是有效的:


$dir = "/home/dir"
unlink($dir . "/*"); # "*" being a match for all strings
rmdir($dir);

回答by Lusitanian

Use globto find all files matching a pattern.

使用glob查找匹配模式的所有文件。

function recursiveRemoveDirectory($directory)
{
    foreach(glob("{$directory}/*") as $file)
    {
        if(is_dir($file)) { 
            recursiveRemoveDirectory($file);
        } else {
            unlink($file);
        }
    }
    rmdir($directory);
}

回答by John Conde

Use glob()to easily loop through the directory to delete files then you can remove the directory.

使用glob()通过目录删除文件轻松地循环,那么你可以删除该目录。

foreach (glob($dir."/*.*") as $filename) {
    if (is_file($filename)) {
        unlink($filename);
    }
}
rmdir($dir);

回答by svens

The glob()function does what you're looking for. If you're on PHP 5.3+ you could do something like this:

glob()功能可以满足您的需求。如果您使用的是 PHP 5.3+,则可以执行以下操作:

$dir = ...
array_walk(glob($dir . '/*'), function ($fn) {
    if (is_file($fn))
        unlink($fn);
});
unlink($dir);

回答by Ahosan Karim Asik

Try easy way:

尝试简单的方法:

$dir = "/home/dir";
array_map('unlink', glob($dir."/*"));
rmdir($dir);

In Function for remove dir:

在删除目录的功能中:

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('..', '.')))  {
                unlinkr($file, $pattern);
                //remove the directory itself
                rmdir($file);
                } else if(is_file($file) and ($file != __FILE__)) {
                // make sure you don't delete the current script
                unlink($file); 
            }
        }
        rmdir($dir);
    }

//call following way:
unlinkr("/home/dir");

回答by Danijel

A simple and effective way of deleting all files and folders recursively with Standard PHP Library, to be specific, RecursiveIteratorIteratorand RecursiveDirectoryIterator. The point is in RecursiveIteratorIterator::CHILD_FIRSTflag, iterator will loop through files first, and directory at the end, so once the directory is empty it is safe to use rmdir().

使用标准 PHP 库递归删除所有文件和文件夹的简单而有效的方法,具体来说是RecursiveIteratorIteratorRecursiveDirectoryIterator。重点在于RecursiveIteratorIterator::CHILD_FIRST标志,迭代器将首先循环遍历文件,最后循环遍历目录,因此一旦目录为空,就可以安全地使用rmdir().

foreach( new RecursiveIteratorIterator( 
    new RecursiveDirectoryIterator( 'folder', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ), 
    RecursiveIteratorIterator::CHILD_FIRST ) as $value ) {
        $value->isFile() ? unlink( $value ) : rmdir( $value );
}

rmdir( 'folder' );

回答by Adam Elsodaney

You can use the Symfony Filesystem component, to avoid re-inventing the wheel, so you can do

您可以使用Symfony Filesystem 组件,以避免重新发明轮子,因此您可以这样做

use Symfony\Component\Filesystem\Filesystem;

$filesystem = new Filesystem();

if ($filesystem->exists('/home/dir')) {
    $filesystem->remove('/home/dir');
}

If you prefer to manage the code yourself, here's the Symfony codebase for the relevant methods

如果你更喜欢自己管理代码,这里是相关方法的 Symfony 代码库

class MyFilesystem
{
    private function toIterator($files)
    {
        if (!$files instanceof \Traversable) {
            $files = new \ArrayObject(is_array($files) ? $files : array($files));
        }

        return $files;
    }

    public function remove($files)
    {
        $files = iterator_to_array($this->toIterator($files));
        $files = array_reverse($files);
        foreach ($files as $file) {
            if (!file_exists($file) && !is_link($file)) {
                continue;
            }

            if (is_dir($file) && !is_link($file)) {
                $this->remove(new \FilesystemIterator($file));

                if (true !== @rmdir($file)) {
                    throw new \Exception(sprintf('Failed to remove directory "%s".', $file), 0, null, $file);
                }
            } else {
                // https://bugs.php.net/bug.php?id=52176
                if ('\' === DIRECTORY_SEPARATOR && is_dir($file)) {
                    if (true !== @rmdir($file)) {
                        throw new \Exception(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
                    }
                } else {
                    if (true !== @unlink($file)) {
                        throw new \Exception(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
                    }
                }
            }
        }
    }

    public function exists($files)
    {
        foreach ($this->toIterator($files) as $file) {
            if (!file_exists($file)) {
                return false;
            }
        }

        return true;
    }
}

回答by Adi

One way of doing it would be:

一种方法是:

function unlinker($file)
{
    unlink($file);
}
$files = glob('*.*');
array_walk($files,'unlinker');
rmdir($dir);

回答by MD Alauddin Al-Amin

for removing all the files you can remove the directory and make again.. with a simple line of code

要删除所有文件,您可以删除目录并再次制作.. 使用简单的代码行

<?php 
    $dir = '/home/files/';
    rmdir($dir);
    mkdir($dir);
?>