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 BurgNov 24, 2014 at 10:27
-
1Yeah, this is a different question that drew different answers. It should not be marked as a duplicate.– Daniel BinghamMay 13, 2015 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);
-
5
-
12Although it's obvious, I'd mention that, for example, 'path/to/temp/*.txt' will remove only txt files and so on.– TertiumMar 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?– yoanoMar 31, 2016 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 HeqAug 7, 2017 at 22:37
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!)
-
38Best answer, thanks. To avoid notices I'd also do
glob("...") ?: []
(PHP 5.4+) because for an empty directoryglob()
returnsfalse
.– mojubaJan 25, 2013 at 1:38 -
22It deletes all files in the current folder, but it returns a warning for subfolders and doesn't delete them.– Key-SixMar 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
-
3To "suppress" the error warnings use
@array_map('unlink', glob("path/to/temp/*"));
– tmaroisAug 16, 2016 at 14:29
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!– guariApr 28, 2017 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. Sep 20, 2018 at 17:44
-
This solution is crashing server - localhost and also online server. Not good solution for me. Thanks.– KamleshSep 29, 2020 at 8:50
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
if(!$fileInfo->isDot()) {
unlink($fileInfo->getPathname());
}
}
-
it should be unlink('/path/to/directory/'.$fileInfo->getFilename()); since unlink takes in the path. Good answer though.– VicJan 4, 2013 at 3:51
-
9You 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
-
2Doesn'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
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);
}
}
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.
-
3Bit unsafe using this method, if
$absolutePatToFolder
is ever empty Jan 4, 2017 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. 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
<?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);
}
?>
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/
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
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."/*"));
}
}
}
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');
<?
//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
?>
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);
}
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);
}
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.
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));
}
This is a simple way and good solution. try this code.
array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));