Sunday, 3 June 2012

Delete non empty directory in php

This article is to discuss how can delete any folder in php.Delete a directory in php is done by
the method rmdir().  But it work only if the directory is empty.That is it can delete empty directories only.   


            In php delete non empty directory is done by first delete contents of folder.
That is delete all files in a folder.Then delete the empty directory using rmdir().

This code will  describe how can php remove non empty directory.   

CODE

<?php
    del('new');

        function del($dir)
         {
            $result=array_diff(scandir($dir),array('.','..'));
             foreach($result as $item)
               {

     if(!@unlink($dir.'/'.$item))
    del($dir.'/'.$item);

                }
        rmdir($dir);
           }

?>



        Here I have defined a function with name del().   It has one parameter which is the  name of the directory to be delete.Here my directory name is 'new'.


        In the   del()    function defenition   $result=array_diff(scandir($dir),array('.','..'));
scandir()   is used to get the name of all files and folders in the directory provided.
array_diff(..,array('.','..'))   is used to remove the default '.' and '..' folders.  Then the remaining array is parsed using  a  foreach  loop.


        First assume the item is a file.So delete it using unlink().  If unlink() returns false  the item will be a directory.  So del()   function is called in  recursive manner with the sub folder name ($item).

 
        After the loop has executed rmdir($dir) will call.Now rmdir() can delete the directory
because the directory will be empty.   Hence delete directory with php is done.  

You can also read :-
Extend maximum execution time of php script

No comments:

Post a Comment

Search This Blog