Deleting All Files From A Folder Using PHP


What is PHP ?

PHP is a widely-used server-side scripting language that is primarily designed for web development. It stands for "Hypertext Preprocessor" and is known for its versatility and ease of use. PHP enables the creation of dynamic web pages by embedding code within HTML, allowing developers to generate dynamic content, interact with databases, handle form data, and perform various other server-side tasks. It provides a wide range of features and functionalities, including support for multiple platforms, extensive libraries, and frameworks that facilitate rapid development. PHP is an open-source language with a large and active community, constantly contributing to its evolution and the creation of numerous plugins and extensions. Its flexibility, scalability, and extensive documentation make it a popular choice for building dynamic websites and web applications.

Deleting All Files From A Folder Using PHP

To delete all the files from a folder using PHP you can use then glob() function and also Scandir() function.

Method 1

Using glob() function

In PHP, the glob() function is used to retrieve file or directory paths that match a specified pattern. It searches for files or directories in a directory based on wildcard characters and returns an array of matches.

Syntax

Then syntax of glob() function is as follows.

array|false glob(string $pattern, int $ flags = 0)

Parameters

  • $pattern: This is the required parameter that represents the pattern to match against files or directories.

  • $flags (optional): This parameter is used to modify the behaviour of the glob() function. It can take various flags to control the matching behaviour. Some commonly used flags include:

  • GLOB_BRACE: Expands {a,b,c} syntax to match multiple patterns.

  • GLOB_ONLYDIR: Matches only directories.

  • GLOB_NOSORT: Returns files in a natural order, without sorting.

Return Value

The glob() function returns an array of file or directory names that match the specified pattern. If no files match the pattern, it returns an empty array. If an error occurs, it returns false.

Example

Here is an example how you can delete all files from a folder using glob() function.

$folderPath = 'path/folder'; 
$fileList = glob($folderPath . '/*');
foreach ($fileList as $file) {
   if (is_file($file)) {
      unlink($file);
   }
}

Explanation of Code

The provided code snippet deletes all files from a specified folder using PHP. It first retrieves a list of files in the folder using the glob() function. Then, it loops through each file in the list, checks if it is a file using is_file(), and if so, deletes it using the `unlink()` function. This code should be used with caution as it permanently removes all files from the folder. Make sure to provide the correct folder path and review before executing the code.

Method 2

Using Scandir()

In PHP, the scandir() function is used to retrieve the list of files and directories within a specified directory. It returns an array of file and directory names.

Syntax

The syntax of Scandir() function is as follows.

array scandir(string $directoryPath, int $sortingOrder = 
SCANDIR_SORT_ASCENDING, resource $context = null)

Parameters

  • $directoryPath: This is the required parameter that represents the path to the directory that you want to scan.

  • $sortingOrder (optional): This parameter specifies the sorting order of the items in the resulting array. It can take the following values:

  • SCANDIR_SORT_ASCENDING (default): Sorts items in ascending order.

  • SCANDIR_SORT_DESCENDING: Sorts items in descending order.

  • SCANDIR_SORT_NONE: Does not perform any sorting.

  • $context (optional): This parameter allows you to specify a context for the directory stream. It is typically used for resource access control.

Return Value

The scandir() function returns an array of strings containing the names of all items (files and directories) within the specified directory. It includes both the item names (. and ..) representing the current and parent directories, respectively.

Example

Here is an example of deleting all files from a folder using Scandir()

function deleteAllFiles($folderPath) {
   $files = scandir($folderPath);
   foreach ($files as $file) {
      if ($file !== '.' && $file !== '..') {
         $filePath = $folderPath . '/' . $file;
            
         if (is_file($filePath)) {
            unlink($filePath);
         }
      }
   }
}

Explanation of Code

The code demonstrates a method named deleteAllFiles() that deletes all files from a specified folder in PHP. It utilizes the scandir() function to obtain an array of files in the folder. By iterating through each item and excluding the current and parent directories, it constructs the file path and checks if the item is a file using is_file(). If it is, the file is deleted using unlink(). Exercise caution when executing this code to prevent unintentional file deletions.

Conclusion

In conclusion, this tutorial has provided a comprehensive guide on how to delete all files from a folder using PHP. The steps outlined in this tutorial can be applied in various scenarios where there is a need to remove multiple files from a particular directory. By understanding the importance of file deletion and the potential use cases, you can leverage the knowledge gained from this tutorial to efficiently manage file systems and maintain data integrity in your PHP projects.

Updated on: 28-Jul-2023

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements