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

半世苍凉 提交于 2019-11-27 01:08:51

问题


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.

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


回答1:


Use glob to find all files matching a pattern.

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



回答2:


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

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



回答3:


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

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



回答4:


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



回答5:


A simple and effective way of deleting all files and folders recursively with Standard PHP Library, to be specific, RecursiveIteratorIterator and RecursiveDirectoryIterator. The point is in RecursiveIteratorIterator::CHILD_FIRST flag, iterator will loop through files first, and directory at the end, so once the directory is empty it is safe to use 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' );



回答6:


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

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

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



回答7:


One way of doing it would be:

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



回答8:


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


来源:https://stackoverflow.com/questions/11267086/php-unlink-all-files-within-a-directory-and-then-deleting-that-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!