I made this function to delete a directory with all its contents recursively, will it work as expected in a production environment ? is it safe ? I don't want to wake up one day with /home contents is gone :D
public static function delTree($dir) {
if(!is_dir($dir)){return false;};
$files = scandir($dir);if(!$files){return false;}
$files = array_diff($files, array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? SELF::delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
Note: I use this function internally, meaning there are no client parameters like directory names is taken from the client before I call it, so there is no chance for traversal attacks, and I check the base path with another function before I call it, for example to delete a client folder I do something like this
$clientsFolderPath = $_SERVER['DOCUMENT_ROOT'] . "/../clients"
$clientFolderPath = "$clientsFolderPath/$clientId";
$realBase = realpath($clientsFolderPath);
$realClientDir = realpath($clientFolderPath);
if ( !$realBase || !$realClientDir || strpos($realClientDir, $realBase) !== 0 ){
//error, log , and exit;
} else {
ExtendedSystemModel::delTree($clientFolderPath);
}