Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting all files from a folder using PHP?

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?

like image 260
getaway Avatar asked Jan 04 '11 13:01

getaway


People also ask

How can I delete all files in a directory in PHP?

unlinkr function recursively deletes all the folders and files in given path by making sure it doesn't delete the script itself. unlinkr("/home/user/temp"); This will delete all files in home/user/temp directory.

How do I delete a file in PHP?

To delete a file in PHP, use the unlink function. Let's go through an example to see how it works. The first argument of the unlink function is a filename which you want to delete. The unlink function returns either TRUE or FALSE , depending on whether the delete operation was successful.

Which function is used in PHP to delete a file?

PHP | unlink() Function The unlink() function is an inbuilt function in PHP which is used to delete files.

How do you delete a file in laravel?

You could use PHP's unlink() method just as @Khan suggested. But if you want to do it the Laravel way, use the File::delete() method instead. $files = array($file1, $file2); File::delete($files);


2 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); 
like image 168
Floern Avatar answered Nov 08 '22 23:11

Floern


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!)

like image 38
Stichoza Avatar answered Nov 08 '22 23:11

Stichoza