You Are Here Home > PHP Script for recursively deleting a folder and all of its...

PHP Script for recursively deleting a folder and all of its contents, subfolders and files

<?php
 
	set_time_limit(900);
 
	delete_folder(dirname(__FILE__) .'/');
 
	function delete_folder($folder) {
		$folder_contents = get_folder_contents($folder);
		if ($folder_contents) {
			foreach ($folder_contents as $__content) {
				// echo $__content['item'] .'<br />';
				if (is_dir($__content['item']))
					delete_folder($__content['item']);
				else
					unlink($__content['item']);
			}
		}
		rmdir($folder);
	}
 
	function get_folder_contents($folder) {
		if( !is_dir($folder) ) {
			return false;
		}
		$return_array = array();
		$count		  = 0;
		if( $dh = opendir($folder) ) {
			while( ($file = readdir($dh)) !== false ) {
				if( $file == '.' || $file == '..' ) continue;
				$return_array[$count]['item']	= $folder .$file .(is_dir($folder .$file) ? DIRECTORY_SEPARATOR : '');
 
				$count++;
			}
			closedir($dh);
		}
		return $return_array;
	}
 
?>

Put it *inside* the folder that you want to delete and run it.
Be very careful when using this code, I warned you! Don’t use this if you don’t know any PHP.

PHP Script for recursively deleting a folder and all of its contents, subfolders and files
Filed under: PHP, Server   Posted by: Codehead

Got a Question?

Get answers here.

3 Comments »

  1.  

    Excelente tip. Thank you for share.

    Comment

  2.  
    function removeDir($dir){
    	$dir = rtrim($dir, '/');
    	$contents = scandir($dir);
    	foreach($contents as $item){
    		if($item != '.' &amp;&amp; $item != '..'){
    			$item = $dir . '/' . $item;
    			if(is_dir($item)){
    				removeDir($item);
    			}else{
    				if(!(@unlink($item))){
    					throw new Exception('Unable to remove file:' . $item);
    				}
    			}
    		}
    	}
    	if(!(@rmdir($dir))){
    		throw new Exception('Unable to remove dir:' . $item);
    	}
    }

    Comment

  3. Codehead:
     

    Thanks Tim, this is what you get for not looking at the list of available functions :)

    Comment

RSS feed for comments on this post. TrackBack URL

Leave a comment