How to recursively delete a directory and its entire contents (files + sub dirs) in PHP?

In PHP if you want to delete the file or directory then keep one thing in mind that you cannot delete the the file or directory directly there is a condition on that i.e. there are some security issues are there so the best way to do this is you first have to delete the data present in the file or the sub files or directories present in it . Then only you are able to delete the directory . And after deleting the sub directories or files use the rmdir function to delete the main directory.

PHP function to delete all files: In the following code, first passing the path of directory which need to delete. It checks whether the file or directory which need to delete is actually present/exist or not. If it does exist then it will open the file check whether there is something in that file or not. If not then delete the directory using rmdir directory. But if any other files are present in the directory if then it will delete the files using unlink function except the . and .. files which means the system files. After deleting all the stuff just use the rmdir function to delete the directory completely.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Variable to store directory name
// which need to delete
$folder = 'temporary_files';
  
// Get the list of all of file names
// in the folder.
$files = glob($folder . '/*');
  
// Loop through the file list
foreach($files as $file) {
      
    // Check for file
    if(is_file($file)) {
          
        // Use unlink function to 
        // delete the file.
        unlink($file);
    }
}
?>

chevron_right


  • Before Removing the files:
  • After Removing the files:

Description:

  • In this above example, deleting all files from a folder called “temp”.
  • List the files in this directory by using PHP glob function. The glob function basically “finds pathnames that match a certain pattern”. In this case, use a wildcard * (asterix) to select everything that is in the “temp” folder.
  • The glob function returns an array of file names that are in the specified folder.
  • Loop through this array.
  • Using the is_file function to check if it is a file and not a parent directory or a sub-directory.
  • Finally, use the unlink function, which deletes the file (if PHP has valid permissions – if not, an E_WARNING error will be thrown and the function will return a boolean FALSE value).
  • Delete all files and sub-directories in a directory: To delete all files and directories in all sub-directories, we can use recursion. Here is an example of a recursive PHP function that deletes every file and folder in a specified directory.



    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    // Function to delete all files
    // and directories
    function deleteAll($str) {
          
        // Check for files
        if (is_file($str)) {
              
            // If it is file then remove by
            // using unlink function
            return unlink($str);
        }
          
        // If it is a directory.
        elseif (is_dir($str)) {
              
            // Get the list of the files in this
            // directory
            $scan = glob(rtrim($str, '/').'/*');
              
            // Loop through the list of files
            foreach($scan as $index=>$path) {
                  
                // Call recursive function
                deleteAll($path);
            }
              
            // Remove the directory itself
            return @rmdir($str);
        }
    }
       
    // Function call
    deleteAll('temporary_files'); 
      
    ?>

    chevron_right

    
    

    Output:

    • Before removing the directory:
    • After removing the directory: The directory is completely deleted.

    The function checks if the $str variable represents a path to a file then it deletes the file using the function unlink. However, if $str represents a directory, then it gets a list of all files in said directory before deleting each one. Finally, it removes the sub-directory itself by using PHP rmdir function.



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :
    Practice Tags :


    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.