Deleting all files from a folder using PHP?

PhpFileDirectoryGlob

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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 call can also handle empty directories ( thanks for the tip, @mojuba!)

Solution 3 - Php

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

Solution 4 - Php

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

Solution 5 - Php

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

Solution 6 - Php

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

Solution 7 - Php

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.

Solution 8 - Php

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

Solution 9 - Php

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/

Solution 10 - Php

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.

Solution 11 - Php

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

Solution 12 - Php

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

Solution 13 - Php

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

Solution 14 - Php

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

Solution 15 - Php

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

Solution 16 - Php

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.

Solution 17 - Php

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

Solution 18 - Php

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongetawayView Question on Stackoverflow
Solution 1 - PhpFloernView Answer on Stackoverflow
Solution 2 - PhpStichozaView Answer on Stackoverflow
Solution 3 - PhpYamikoView Answer on Stackoverflow
Solution 4 - PhpJakeParisView Answer on Stackoverflow
Solution 5 - PhpPoelinca DorinView Answer on Stackoverflow
Solution 6 - PhpHaim EvgiView Answer on Stackoverflow
Solution 7 - PhpDario CornoView Answer on Stackoverflow
Solution 8 - PhpStampedeXVView Answer on Stackoverflow
Solution 9 - PhpJoyGuruView Answer on Stackoverflow
Solution 10 - PhpTofeeqView Answer on Stackoverflow
Solution 11 - PhptommyView Answer on Stackoverflow
Solution 12 - PhpAmyStephenView Answer on Stackoverflow
Solution 13 - Phpuser5579724View Answer on Stackoverflow
Solution 14 - PhpTiago Silva PereiraView Answer on Stackoverflow
Solution 15 - PhpMehmetView Answer on Stackoverflow
Solution 16 - PhpMAChitgarhaView Answer on Stackoverflow
Solution 17 - PhptziView Answer on Stackoverflow
Solution 18 - PhpInventor BalaView Answer on Stackoverflow