Delete files and folders recursively using PHP


unlinkr function recursively deletes all the folders and files in given path by making sure it doesn’t delete the script itself.

    function unlinkr($dir, $pattern = "*") {
        // find all files and folders matching pattern
        $files = glob($dir . "/$pattern"); 
    
        //interate thorugh the files and folders
        foreach($files as $file){ 
        //if it is a directory then re-call unlinkr function to delete files inside this directory     
            if (is_dir($file) and !in_array($file, array('..', '.')))  {
                echo "<p>opening directory $file </p>";
                unlinkr($file, $pattern);
                //remove the directory itself
                echo "<p> deleting directory $file </p>";
                rmdir($file);
            } else if(is_file($file) and ($file != __FILE__)) {
                // make sure you don't delete the current script
                echo "<p>deleting file $file </p>";
                unlink($file); 
            }
        }
    }

if you want to delete all files and folders where you place this script then call it as following

    //get current working directory
    $dir = getcwd();
    unlinkr($dir, "*");

if you want to just delete the php files then call it as following

    unlinkr($dir, "*.php");

you can use any other path to delete the files as well

    unlinkr("/home/user/temp", "*");

This will delete all files in home/user/temp directory.

Advertisements

One thought on “Delete files and folders recursively using PHP

  1. druidsolutions says:

    Thank you for good script. Would you be so kind to help me change code that delete script itself. I think that is in this part and ($file != __FILE__)) but my PHP is not very good to change it myself. Thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s