How to delete single or multiple files in a directory using PHP
  John Mwaniki /   22 Sep 2021

How to delete single or multiple files in a directory using PHP

In your day-to-day web projects, you happen to work with multiple files of different types such as .php, .html, .css, images, etc.

Over time, you may get to a point where you no longer need some of these files and want to delete them.

This can be an overwhelming task especially if they have piled up to huge numbers and want to select and delete specific ones with a certain filename, or those that meet certain criteria.

Luckily, you can delete them programmatically with a PHP script.

In this article, you will learn multiple methods in which you can delete single or multiple files in a given directory programmatically using PHP.

Deleting a single file using PHP

To delete a single file, use the inbuilt PHP unlink() function. All you need is to pass the name of the file to the function and it will be deleted.

Syntax

unlink($filename);

Example 1

<?php
$filename = "image.jpg";
unlink($filename);
?>

The above code deletes a file named image.jpg placed in the same directory as the PHP file with the code.

If the file to be deleted happens not to be in the same directory with the PHP script then you need to include the relative path to in the unlink() function as in the example below.

Example 2

I have created a PHP file namely "filedeletion.php" and placed it in the directory path: "/opt/lampp/htdocs/www/demos/" as shown below:

File deletion with PHP

I have as well placed a file namely "logo.png" and placed it in the directory path: "/opt/lampp/htdocs/www/demos/images/" as shown below:

File to be deleted with PHP

The relative path to the file "logo.png" from the PHP script is "images/logo.png". So I have added the code below into the "filedeletion.php" file.

<?php
$file = "images/logo.png";
unlink($file); //You can also add "images/logo.png" directly inside unlink()
?>

Running the above code completely deletes the "logo.png" file from the "images" folder.

File deleted with PHP

Please note you need to have write permission to the directory in which the file to be deleted is located. If you don't have that permission you will get the error below:

Warning: unlink(images/logo.png): Permission denied in /opt/lampp/htdocs/www/demos/filedeletion.php on line 3

You can add an if statement to the code above to display a success message on successful deletion, or a failure message on deletion error as below:

<?php
$file = "images/logo.png";
if (unlink($file)) {
   echo 'The file was deleted successfully!';
} else {
   echo 'An error occurred in file deletion';
}
?>

If you try to delete a file that does not exist in the directory, you will get the error below.

Warning: unlink(images/logos.png): No such file or directory in /opt/lampp/htdocs/www/demos/filedeletion.php on line 3

It is therefore important to first check whether the file already exists before trying to delete it.

We use the in-built PHP file_exists() function to do the check. It returns true if the file exists or false if no such file exists in the specified directory.

Syntax

file_exists($filename)

In the same way as the unlink() function, pass the file path if the file is not in the same directory as the PHP script.

Example

The code below executes the deletion only after we have confirmed that the file exists. Else, it will return an error message that the file doesn't exist.

<?php
$file = "images/logo.png";
if(file_exists($file)){
 if(unlink($file)){
   echo 'The file was deleted successfully!';
 }
 else{
   echo 'An error occurred in file deletion';
 }
}
else{
  echo 'The file you are trying to delete does not exist';
}
?>

If you have multiple files that you want to delete and have their names saved in a database table, or in an array, you can iterate the above code inside a while or a foreach loop like in the example below.

<?php
$files = array("image1.png","image2.webp","image3.gif","image4.jpg","image5.jpeg");
foreach ($files as $file) {
 $filepath = "images/".$file;
 if(file_exists($filepath)){
   if(unlink($filepath)){
    echo 'The file was deleted successfully!';
   }
   else{
    echo 'An error occurred in file deletion';
   }
 } 
 else{
   echo 'The file does not exist';
  }
}
?>

 

Deleting multiple or all the files in a directory using PHP

There are several ways to delete all the files in a directory using PHP. In these methods, we still use the same directory as in the earlier examples for demonstration purposes.

Method 1

In this method, we use the glob() function to get the names of all the files in the directory. Then use the file the foreach loop to iterate through the file names. Then we use the is_file() function to check whether the name of the file is valid and lastly unlink() to delete the files as shown in the example below:

<?php
$files = glob('images/*'); // To get a list of the files in the images directory
foreach($files as $file){ // To iterate through the files
  if(is_file($file)) {  //To check whether the filename is valid
    unlink($file); // To delete the file
  }
}
?>

Method 2

In this method, we generate a list of all the files in our directory using the glob() function, filter that list using the array_filter() function and lastly map them into the unlink() function using array_map() function.

Example

<?php
$files = glob("images/*"); 
$filteredfiles = array_filter((array) $files);
array_map("unlink", $filteredfiles);
?>

You can simplify the above code into one line as below:

<?php
array_map('unlink', array_filter((array) glob("images/*")));
?>


Deleting multiple files of a given file type

From the above methods and examples, you can now comfortably delete single or all the files in a directory using PHP.

But what if you have a directory with all sorts of files eg. .html, .php, .pdf, .css, .png, .jpg, etc. In this case, let's say you want to delete all the files of type .png and leave the rest intact. The above methods won't help you.

In this method, we do exactly that. The method is similar to the above only that we specify the file type of the files we want to delete.

We use the glob() function to search for all the files of type .png in the "images" directory and then map them to the unlink() function using the array_map() function as shown in the example below:

<?php
$folder = 'images/';
array_map('unlink', glob("{$folder}*.tmp"));
?>


Deleting hidden files using PHP

You can't delete hidden files using the above methods/examples. To delete the hidden files using PHP code, you will need to be more specific in the glob() function and do it as below:

<?php
$files = glob('path/to/file/{,.}*', GLOB_BRACE);
array_map('unlink', $files);
?>

There are still a number of additional ways in which you can delete multiple files in a directory. All of them use the unlink() function but have different methods of accessing the files and iterating through them.