VOOZH about

URL: https://www.geeksforgeeks.org/php/deleting-all-files-from-a-folder-using-php/

⇱ Deleting all files from a folder using PHP - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Deleting all files from a folder using PHP

Last Updated : 11 Jul, 2025
In PHP, files from a folder can be deleted using various approaches and inbuilt methods such as unlink, DirectoryIterator and DirectoryRecursiveIterator. Some of these approaches are explained below: Approach 1:
  • Generate a list of files using glob() method
  • Iterate over the list of files.
  • Check whether the name of files is valid.
  • Delete the file using unlink() method.
Example: Output: Before Running the code: 👁 Image
After Running the code: 👁 Image
Note: Hidden files can be included in the file removal operation by addition of the below code: Approach 2: Example: Approach 3:
  • Generate list of files using DirectoryIterator.
  • Iterate over the list of files.
  • Validate the file while checking if the file directory has a dot or not.
  • Using the getPathName method reference, delete the file using unlink() method.
Example: Approach 4:
  • Generate list of all directory hierarchies inside the given folder directory using RecursiveDirectoryIterator
    $dir = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
    $dir = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
  • FilesystemIterator::SKIP_DOTS is used to ignore dots while generating list of files.
  • RecursiveIteratorIterator::CHILD_FIRST is used for choosing files present at root directory.
  • Iterate over the file list and remove folders and files according to the specification.
Example:
Comment