Gordonmac Dot Com

Mostly a web development blog

Recursive file deletion with PHP

Posted: February 18th, 2008 | Tags: | Posted in: PHP, Tutorials
Note: This tutorial was originally published in 2008. The tips and techniques explained may be outdated.

This is a handy PHP function (I can’t remember where I found it) which performs a recursive deletion of every file in a given directory. I’ve been using it to periodically flush cache files created by my CMS on this site.

function destroy($dir) { $mydir = opendir($dir); while(false !== ($file = readdir($mydir))) { if($file != ”.” && $file != ”..”) { chmod($dir.$file, 0777); if(is_dir($dir.$file)) { chdir(’.’); destroy($dir.$file.’/’); rmdir($dir.$file) or die(‘No deletey ’.$dir.$file); } else unlink($dir.$file) or die(‘No deletey ’.$dir.$file); } } closedir($mydir); }

Example usage

Set the server path to the directory:

define(‘PATH’, ”/path/to/directory/”);

Then let rip…

destroy(PATH);

Have fun, but use with caution!