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?
-
14It'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
$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);
-
4
-
7Although 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 7 '17 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 call can also handle empty directories ( thanks for the tip, @mojuba!)
-
34Best answer, thanks. To avoid notices I'd also do
glob("...") ?: []
(PHP 5.4+) because for an empty directoryglob()
returnsfalse
. – mojuba Jan 25 '13 at 1:38 -
17It deletes all files in the current folder, but it returns a warning for subfolders and doesn't delete them. – Key-Six Mar 5 '14 at 8: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 9: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 6:38
-
3
Here is a more modern approach using the Standard PHP Library (SPL).
$dir = "path/to/directory";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
$file->isDir() ? rmdir($file) : unlink($file);
}
return true;
-
3This 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
-
1For 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 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. – Vic Jan 4 '13 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 – Josh Holloway Jan 10 '13 at 9:38
-
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'? – 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);
}
}
<?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);
}
?>
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.
-
2Bit unsafe using this method, if
$absolutePatToFolder
is ever empty – Lawrence Cherone Jan 4 '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 3 '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. 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
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/
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."/*"));
}
}
}
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.
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);
}
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));
}
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.