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?
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.
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.
PHP | unlink() Function The unlink() function is an inbuilt function in PHP which is used to delete files.
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);
$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);
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With