How can PHP be used to delete directories and their contents on a server?
To delete directories and their contents on a server using PHP, you can use the `rmdir()` function to delete the directory itself and the `unlink()` function to delete all files within the directory. You can recursively delete directories by using a combination of these functions along with `scandir()` to get the list of files and subdirectories within a directory.
function deleteDirectory($dir) {
if (!file_exists($dir)) {
return;
}
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? deleteDirectory("$dir/$file") : unlink("$dir/$file");
}
rmdir($dir);
}
// Usage
deleteDirectory('/path/to/directory');
Keywords
Related Questions
- What function can be used in PHP to remove escape characters like \ from a string?
- How can developers ensure that tokens generated for user authentication are random and secure, without compromising user data privacy?
- How can one troubleshoot errors related to the SVN module not appearing in phpinfo despite being included in the php.ini file?