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
- What best practice should be followed when deleting files from a server after deleting content from a database in PHP?
- What are some common pitfalls to avoid when setting up an Apache server for PHP development?
- How can using double quotation marks in PHP echo statements affect the output in different browsers?