I there a way I can use RegExp or Wildcard searches to quickly delete all files within a folder, and then remove that folder in PHP, WITHOUT using the "exec" command? My server does not give me authorization to use that command. A simple loop of some kind would suffice.
I need something that would accomplish the logic behind the following statement, but obviously, would be valid:
$dir = "/home/dir" unlink($dir . "/*"); # "*" being a match for all strings rmdir($dir);
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/*") ) );
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
rm command – removes a directory/folder along with all the files and sub-directories in it.
The unlink() function is an inbuilt function in PHP which is used to delete files. It is similar to UNIX unlink() function. The $filename is sent as a parameter that needs to be deleted and the function returns True on success and false on failure. Syntax: unlink( $filename, $context )
Use glob
to find all files matching a pattern.
function recursiveRemoveDirectory($directory) { foreach(glob("{$directory}/*") as $file) { if(is_dir($file)) { recursiveRemoveDirectory($file); } else { unlink($file); } } rmdir($directory); }
Use glob()
to easily loop through the directory to delete files then you can remove the directory.
foreach (glob($dir."/*.*") as $filename) { if (is_file($filename)) { unlink($filename); } } rmdir($dir);
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