How can PHP be used to recursively delete files within a directory?
To recursively delete files within a directory using PHP, we can use a combination of `scandir()` to get a list of files and directories within the target directory, and `unlink()` to delete files. We also need to check if each item is a file or a directory, and if it's a directory, recursively call the function to delete files within that directory.
function deleteFiles($dir){
$files = array_diff(scandir($dir), array('.','..'));
foreach($files as $file){
$path = $dir.'/'.$file;
if(is_dir($path)){
deleteFiles($path);
}else{
unlink($path);
}
}
rmdir($dir);
}
// Usage
$directory = 'path/to/directory';
deleteFiles($directory);
Related Questions
- How can regular expressions be used to filter specific HTML tags from source code in PHP?
- In what way can a cronjob be utilized to automate the process of deleting entries beyond the 20th post in a PHP userbox application, as suggested by a forum member?
- What are best practices for handling SQL queries in PHP to avoid duplicate results?