366

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?

2
  • 19
    It's a good thing this question was answered down below before it was marked as duplicate. The answers below are way better than the linked answered question. Plus the question is different, this question asks to empty a directory, not delete.
    – Bart Burg
    Nov 24, 2014 at 10:27
  • 1
    Yeah, this is a different question that drew different answers. It should not be marked as a duplicate. May 13, 2015 at 19:51

18 Answers 18

724
$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

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);
7
  • 5
    Also there is DirectoryIterator or DirectoryRecursiveIterator.
    – Eugene
    Jan 4, 2011 at 14:28
  • 12
    Although it's obvious, I'd mention that, for example, 'path/to/temp/*.txt' will remove only txt files and so on.
    – Tertium
    Mar 31, 2015 at 17:44
  • Does this also works for relative paths? So let's say the full path is "/var/www/html/folder_and_files_to_delete/" And the delete script is placed in "/var/www/html/delete_folders_and_files.php". Can I just take "folder_and_files_to_delete" as path?
    – yoano
    Mar 31, 2016 at 17:58
  • 1
    @yoano yes sure, as long the relative path is correct.
    – Floern
    Mar 31, 2016 at 18:04
  • Is glob OK to use if the directory has tens of thousands or hundreds of thousands of files in it?
    – Dave Heq
    Aug 7, 2017 at 22:37
305

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

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

This can also handle empty directories (thanks for the tip, @mojuba!)

7
  • 38
    Best answer, thanks. To avoid notices I'd also do glob("...") ?: [] (PHP 5.4+) because for an empty directory glob() returns false.
    – mojuba
    Jan 25, 2013 at 1:38
  • 22
    It deletes all files in the current folder, but it returns a warning for subfolders and doesn't delete them.
    – Key-Six
    Mar 5, 2014 at 8:48
  • 8
    @Ewout : Even if we combine Stichoza's and Moujuba's answer as your give returns the same warning for subfolders and it doesn't delete them May 21, 2014 at 6:38
  • 7
    Unfortunately this does not delete subfolders.
    – tmarois
    Aug 16, 2016 at 14:25
  • 3
    To "suppress" the error warnings use @array_map('unlink', glob("path/to/temp/*"));
    – tmarois
    Aug 16, 2016 at 14:29
115

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

$dir = "path/to/directory";
if(file_exists($dir)){
    $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
    $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
    foreach ( $ri as $file ) {
        $file->isDir() ?  rmdir($file) : unlink($file);
    }
}
3
  • 4
    This works nicely, when you have no SSH access and FTP takes literally hours to recursive delete lots of files and folders... with those lines I deleted 35000 files in less than 3 seconds!
    – guari
    Apr 28, 2017 at 15:34
  • 3
    For PHP 7.1 users : $file->getRealPath() must be used instead of $file. Otherwise, PHP will give you an error saying that unlink requires a path, not an instance of SplFileInfo. Sep 20, 2018 at 17:44
  • This solution is crashing server - localhost and also online server. Not good solution for me. Thanks.
    – Kamlesh
    Sep 29, 2020 at 8:50
73
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}
3
  • it should be unlink('/path/to/directory/'.$fileInfo->getFilename()); since unlink takes in the path. Good answer though.
    – Vic
    Jan 4, 2013 at 3:51
  • 9
    You could even do unlink($fileInfo->getPathname()); which would give you the full path to the file. php.net/manual/en/directoryiterator.getpathname.php Jan 10, 2013 at 9:38
  • 2
    Doesn't 'DirectoryIterator' also iterate over subdirectories? If so 'unlink' would generate a warning in such cases. Shouldn't the body of the loop look more like in Yamiko's answer instead and check each entry if it's a file before calling 'unlink'? May 21, 2018 at 20:58
24

This code from 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);
    }
}
17
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}
12

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 :

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.

10
  • 3
    Bit unsafe using this method, if $absolutePatToFolder is ever empty Jan 4, 2017 at 16:03
  • @LawrenceCherone Are other alternatives more secure?
    – robsch
    Apr 3, 2017 at 9:41
  • 3
    @LawrenceCherone I hope noone runs php with root permissions nowadays. Being serious, I expect the input to be "secure", as all of the above functions. Apr 3, 2017 at 13:16
  • The most voted solutions don't work in dev environments where www or www-data is not the owner. It's up to the server admin to ensure the proper rights of the folder are set. exec is an invaluable tool for getting things done, and with great power, etc. stackoverflow.com/a/2765171/418974 Apr 14, 2017 at 19:25
  • 2
    may want to use /* just to be sure :-)
    – commonpike
    Dec 21, 2018 at 9:14
11

See readdir and unlink.

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

The simple and best way to delete all files from a folder in 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/

5

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

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

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.

1
  • 1
    Oldie but goodie! Use as example in classroom and it was a hit!
    – Woody
    Apr 14, 2021 at 1:06
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."/*"));
        }
    }
}
0
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

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

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

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

I've built a really simple package called "Pusheh". Using it, you can clear a directory or remove a directory completely (Github link). It's available on Packagist, also.

For instance, if you want to clear Temp directory, you can do:

Pusheh::clearDir("Temp");

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

If you're interested, see the wiki.

0
0

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

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

This is a simple way and good solution. try this code.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.