W3docs

How to Remove Files from Folder with PHP

PHP does not have a specific undo for what you delete from anywhere. This snippet will represent how to remove files from folder permanently using 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 <kbd class="highlighted">glob()</kbd> 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 <kbd class="highlighted">unlink()</kbd> method.

Here is an example:

tex

php delete file(s)

<?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 <kbd class="highlighted">glob()</kbd> method. First, it is necessary to create a files’ list with the <kbd class="highlighted"> glob()</kbd> method. The next step is implementing the <kbd class="highlighted">array_filter()</kbd> method. Then, it comes to mapping the list to <kbd class="highlighted">unlink()</kbd> method with <kbd class="highlighted">array_map</kbd>.

Here is how to do that:

php delete files

<?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 <kbd class="highlighted">unlink()</kbd>.

Here is an example:

php delete file directoryiterator

<?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.