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);
You can use the Symfony Filesystem component, to avoid re-inventing the wheel, so you can do
If you prefer to manage the code yourself, here's the Symfony codebase for the relevant methods
A simple and effective way of deleting all files and folders recursively with Standard PHP Library, to be specific, RecursiveIteratorIterator and RecursiveDirectoryIterator. The point is in
RecursiveIteratorIterator::CHILD_FIRST
flag, iterator will loop through files first, and directory at the end, so once the directory is empty it is safe to usermdir()
.One way of doing it would be:
The
glob()
function does what you're looking for. If you're on PHP 5.3+ you could do something like this:Try easy way:
In Function for remove dir:
Use
glob()
to easily loop through the directory to delete files then you can remove the directory.