SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Get my greedy down dotJoon's Avatar
    Join Date
    Apr 2003
    Location
    daejeon, South Korea
    Posts
    2,223
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    delete directory

    Code:
    $file = 'myFile.php'; 
    if (file_exists($file)) { 
        unlink($file); 
    }
    The code above deletes myFile.php.

    This time, I like to delete myDirectory instead of myFile.php.
    How can I delete myDirectory ?

    The would-be code below doesn't work correctly, but I hope it shows what I want.
    Code:
    $directory = 'myDirectoy'; 
    if (directory_exists($directory)) { 
        delete($directory); 
    }
    Last edited by dotJoon; Jun 25, 2013 at 15:11. Reason: adding

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,436
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Hi dotJoon,

    The function you need is actually rmdir. The PHP documentation has a full list of all the filesystem functions which you might find useful.

  3. #3
    SitePoint Member
    Join Date
    Jun 2010
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    To remove an entire directory along with all sub directories recursively use the following code snippet.

    rmdirr('path/to/dir');

    Code:
    /**
    	Function to remove directory
    	* Depends on cleardir
    */
    function rmdirr ($dir) 
    {
        if (is_dir ($dir) && !is_link ($dir)) 
        {
            return cleardir ($dir) ? rmdir ($dir) : false;
        }
        
        return unlink ($dir);
    }
    
    /**
    	Function to clear a directory recursively
    	* Depends on rmdirr
    */
    function cleardir ($dir) 
    {
        if (!($dir = dir ($dir))) 
        {
            return false;
        }
        while (false !== $item = $dir->read()) 
        {
            if ($item != '.' && $item != '..' && !rmdirr ($dir->path . DIRECTORY_SEPARATOR . $item)) 
            {
                $dir->close();
                return false;
            }
        }
        $dir->close();
        return true;
    }
    Last edited by silv3r.m00n; Jun 27, 2013 at 21:53. Reason: proper formatting


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •