Have you ever tried to manage files and folders from PHP? In some cases it makes good sense to manage some files with PHP. Say you generate images, PDF files or downloadable archives from your scripts. You may want to store dem in a file structure, instead of creating them again and again on every request.
Sometimes you also need to delete files, sometimes even large groups of files or directories including all their subdirectories. The default functionality in PHP and Unix is very careful when it comes to deleting stuff recursively. Below is a function which enables you do do that, but with the security feature of adding a root directory, from which everything must origin – tu avoid unpleasant dataloss.
function removeDir($dir, $root) { if (strlen($root) < 2 || $root != substr($dir, 0, strlen($root))) return false; if (file_exists($dir)) { if (is_dir($dir)) { $files = scandir($dir); foreach($files as $file) { if ($file != '.' && $file != '..') { $file = $dir.$file; if (is_dir($file)) { if (!removeDir($file, $root)) return false; } else { if (!unlink($file)) return false; } } } return rmdir($dir); } else return unlink($file); } else return true; }
You can simply invoke this function by writing:
removeDir('/my/path/to/dir', '/my/path');
The first argument is the dir to delete. The second is a root dir, which any deleted directory must be within.
No comments yet (leave a comment)