How to Remove Files from Folder with PHP

Using the glob() Method

Let’s see what steps are necessary to be taken to delete files with this method. First of all, you should create a files list with the glob() method. The second step is the iteration over that list. Then, you should inspect whether its a file or not. And, finally, it’s time to delete the given file with the unlink() method.

Watch a course Learn object oriented PHP

Here is an example:

tex
<?php

// PHP program for deleting all
// file from a folder

// Folder path to be flushed
$folder_path = "myw3docs";

// List of name of files inside
// specified folder
$files = glob($folder_path . '/*');

// Delete all the files of the list
foreach ($files as $file) {
  if (is_file($file)) {
    // Deleting the given file
    unlink($file);
  }
}

?>

Or you can choose to apply a short code for the glob() method. First, it is necessary to create a files’ list with the glob() method. The next step is implementing the array_filter() method. Then, it comes to mapping the list to unlink() method with array_map.

Here is how to do that:

<?php
// PHP program for deleting all files from a folder

// Delete all the files inside the given folder
array_map('unlink', array_filter(glob("myw3Docs/*"), 'is_file'));

?>

Using DirectoryIterator

In the framework of this approach, it is required to create a list of files with DirectoryIterator. Then, iterate over it. Afterwards, you should validate the files during the process of testing whether the directory includes a dot. Finally, apply the getPathName method reference, deleting the file with unlink().

Here is an example:

<?php
// PHP program for deleting all the files
// from a folder

// Folder path to be flushed
$folder_path = 'myw3docs/';

// Assign files inside the directory
$dir = new DirectoryIterator(dirname($folder_path));

// Delete all the files in the list
foreach ($dir as $fileinfo) {
  if (!$fileinfo->isDot() && $fileinfo->isFile()) {
    // Deleting the given file
    unlink($fileinfo->getPathname());
  }
}

?>

In this snippet, we showed you the most common and efficient ways to delete files from the folder with PHP.