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?
-
19It'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 '14 at 10:27
-
1Yeah, this is a different question that drew different answers. It should not be marked as a duplicate. – Daniel Bingham May 13 '15 at 19:51
18 Answers
$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);

- 33,559
- 24
- 104
- 119
-
5
-
12Although it's obvious, I'd mention that, for example, 'path/to/temp/*.txt' will remove only txt files and so on. – Tertium Mar 31 '15 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 '16 at 17:58
-
1
-
Is glob OK to use if the directory has tens of thousands or hundreds of thousands of files in it? – Dave Heq Aug 07 '17 at 22:37
-
@Floern what if i also want to delete sub folders and contents inside it the current code only deletes files present and not the folders inside – Akshay Shrivastav Feb 11 '20 at 12:23
-
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!)

- 4,491
- 2
- 23
- 24
-
37Best answer, thanks. To avoid notices I'd also do `glob("...") ?: []` (PHP 5.4+) because for an empty directory `glob()` returns `false`. – mojuba Jan 25 '13 at 01:38
-
21It deletes all files in the current folder, but it returns a warning for subfolders and doesn't delete them. – Key-Six Mar 05 '14 at 08:48
-
2Combining Stichoza's and mojuba's answers: `array_map('unlink', ( glob( "path/to/temp/*" ) ? glob( "path/to/temp/*" ) : array() ) );` – Ewout Apr 23 '14 at 09:39
-
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 – Sulthan Allaudeen May 21 '14 at 06:38
-
7
-
3To "suppress" the error warnings use `@array_map('unlink', glob("path/to/temp/*"));` – tmarois Aug 16 '16 at 14:29
-
1@mojuba I have been coding in PHP for quite a long time and yet never knew we can `$b = $a?:[]` things - I used to `$b = $a ? $a : []` Thanks a lot for this!! – Jay Dadhania Apr 04 '20 at 14:26
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);
}
}
-
4This 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 '17 at 15:34
-
3For 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. – KeineMaster Sep 20 '18 at 17:44
-
This solution is crashing server - localhost and also online server. Not good solution for me. Thanks. – Kamlesh Sep 29 '20 at 08:50
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
if(!$fileInfo->isDot()) {
unlink($fileInfo->getPathname());
}
}

- 11,056
- 3
- 42
- 65
-
it should be unlink('/path/to/directory/'.$fileInfo->getFilename()); since unlink takes in the path. Good answer though. – Vic Jan 04 '13 at 03:51
-
9You could even do unlink($fileInfo->getPathname()); which would give you the full path to the file. http://php.net/manual/en/directoryiterator.getpathname.php – Josh Holloway Jan 10 '13 at 09:38
-
1Doesn'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'? – Andreas Linnert May 21 '18 at 20:58
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);
}
}

- 30,738
- 21
- 105
- 131

- 9,577
- 2
- 39
- 43
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}

- 123,187
- 45
- 217
- 223
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.

- 1,129
- 11
- 19
-
3Bit unsafe using this method, if `$absolutePatToFolder` is ever empty – Lawrence Cherone Jan 04 '17 at 16:03
-
-
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. – Dario Corno Apr 03 '17 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. http://stackoverflow.com/a/2765171/418974 – Christian Bonato Apr 14 '17 at 19:25
-
@LawrenceCherone you are totally correct my answer was meant for a very specific situation, just for performance reasons. Modified my answer according to your notes. – Dario Corno Sep 28 '17 at 13:37
-
2
-
I would also add a validation against $absolutePatToFolder to ensure that it's not empty if(strlen($absolutePatToFolder)){ /* above code here */ } – Oliver M Grech Feb 26 '19 at 10:59
-
@ChristianBonato agreed that shell commands are the way to go. but why can't the owner be www or www-data in a dev environment? – David Oct 11 '19 at 17:32
-
@David - Not saying it can't. My comment was referring to cases where the folder or files do not belong to "www" or "www-data" (or whatever the webserver Unix user may be). PHP fires 'exec' as the webserver user. Therefore exec may not work on folder or files with different ownership. – Christian Bonato Oct 12 '19 at 23:31
-
A bit less agressive `exec("find ./path/ -iname '*.html' -exec rm {} \;");` – NVRM Jun 17 '20 at 19:28
<?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);
}
?>

- 30,738
- 21
- 105
- 131

- 2,715
- 2
- 24
- 40
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/

- 1,803
- 20
- 11
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.

- 2,523
- 1
- 23
- 20
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."/*"));
}
}
}

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

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

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

- 17,769
- 16
- 66
- 164

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

- 111
- 2
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.

- 3,728
- 2
- 33
- 40
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));
}

- 8,719
- 2
- 25
- 45
This is a simple way and good solution. try this code.
array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));

- 580
- 5
- 9