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: