What is the best practice for deleting a directory with contents in PHP?
When deleting a directory with contents in PHP, it is best practice to recursively delete all files and subdirectories within the directory before removing the directory itself. This ensures that all contents are properly removed and prevents any errors from occurring.
function deleteDirectory($dir) {
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
// Usage
$directory = 'path/to/directory';
deleteDirectory($directory);
Related Questions
- Are there best practices for managing MediaWiki installations to ensure smooth operation and access to all features?
- How can the issue of headers already sent be resolved in PHP when using session_start()?
- What are the best practices for retrieving existing records from a database and displaying them on a webpage using PHP?