- How to delete single or multiple files in a directory using PHP
- Deleting a single file using PHP
- Syntax
- Syntax
- Deleting multiple or all the files in a directory using PHP
- Method 1
- Method 2
- Deleting multiple files of a given file type
- Deleting hidden files using PHP
- Related Articles
- PHP: Delete all files from a folder.
- Deleting files in sub-folders.
- PHP Delete File
- Introduction to the PHP delete file function
- PHP delete file examples
- 1) Simple PHP delete file example
- 2) Delete all files in a directory that match a pattern
- Summary
- Delete ALL Files and Subfolders from Folder in PHP
- Delete All Files from Folder in PHP:
- PHP Function to Delete All Files from Folder:
- Usage:
- Delete Only Particular File Type from Folder:
- Delete Files Older than X Days from Folder:
- Delete All Files and Sub Folders from a Folder in PHP:
- Function Usage:
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
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.
I have created a PHP file namely «filedeletion.php» and placed it in the directory path: «/opt/lampp/htdocs/www/demos/» as shown below:
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:
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.
Running the above code completely deletes the «logo.png» file from the «images» folder.
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:
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
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.
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.
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.
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:
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.
You can simplify the above code into one line as below:
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:
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:
*', 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.
Related Articles
PHP: Delete all files from a folder.
In this guide, we are going to show you how to delete all files in a folder using PHP.
Our first example is pretty straight-forward, as we simply loop through the files and then delete them.
Take a look at the following code sample.
//The name of the folder. $folder = 'temporary_files'; //Get a list of all of the file names in the folder. $files = glob($folder . '/*'); //Loop through the file list. foreach($files as $file) < //Make sure that this is a file and not a directory. if(is_file($file))< //Use the unlink function to delete the file. unlink($file); >>
- In this example, we will be deleting all files from a folder called “temporary_files”.
- We list the files in this directory by using PHP’s glob function. The glob function basically finds pathnames that match a certain pattern. In this case, we use a wildcard (asterix) to specify that we want to select everything that is inside the “temporary_files” folder.
- The glob function returns an array of file names that are in the specified folder.
- We then loop through this array.
- Using the is_file function, we check to see if it is a file and not a parent directory or a sub-directory.
- Finally, we use the unlink function, which deletes the file.
Deleting files in sub-folders.
To delete all files and directories in all sub-directories, we can use recursion.
Here is an example of a recursive PHP function that deletes every file and folder in a specified directory.
function deleteAll($str) < //It it's a file. if (is_file($str)) < //Attempt to delete it. return unlink($str); >//If it's a directory. elseif (is_dir($str)) < //Get a list of the files in this directory. $scan = glob(rtrim($str,'/').'/*'); //Loop through the list of files. foreach($scan as $index=>$path) < //Call our recursive function. deleteAll($path); >//Remove the directory itself. return @rmdir($str); > > //call our function deleteAll('temporary_files');
The function above basically checks to see if the $str variable represents a path to a file. If it does represent a path to a file, it deletes the file using the function unlink.
However, if $str represents a directory, then it gets a list of all files in said directory before deleting each one.
Finally, it removes the sub-directory itself by using PHP’s rmdir function.
PHP Delete File
Summary: in this tutorial, you will learn how to delete a file in PHP using the unlink() function.
Introduction to the PHP delete file function
To delete a file, you use the unlink() function:
unlink ( string $filename , resource $context = ? ) : bool
Code language: PHP (php)
The unlink() function has two parameters:
- $filename is the full path to the file that you want to delete.
- $context is a valid context resource.
The unlink() function returns true if it deletes the file successfully or false otherwise. If the $filename doesn’t exist, the unlink() function also issues a warning and returns false .
PHP delete file examples
Let’s take some examples of using the unlink() function.
1) Simple PHP delete file example
The following example uses the unlink() function to delete the readme.txt file:
$filename = 'readme.txt'; if (unlink($filename)) < echo 'The file ' . $filename . ' was deleted successfully!'; > else < echo 'There was a error deleting the file ' . $filename; >
Code language: HTML, XML (xml)
2) Delete all files in a directory that match a pattern
The following example deletes all files with the .tmp extension:
$dir = 'temp/'; array_map('unlink', glob("*.tmp"));
Code language: HTML, XML (xml)
- First, define a variable that stores the path to the directory in which you want to delete files.
- Second, use the glob() function to search for all files in the directory $dir that has the *.tmp extension and pass it result to the array_map() function to delete the files.
Generally, you can change the pattern to delete all matching files in a directory using the array_map() , unlink() and glob() functions.
Summary
Delete ALL Files and Subfolders from Folder in PHP
Hi! Today let’s see how to delete all files and sub-folders from a folder using php. If your website allows user uploaded contents then I bet you might want to do regular clean ups to free up more space in web server. Like deleting all files of a user without activity for long time, deleting files older than 3 months etc. Whatever the reason, doing such clean-up manually is a tedious task. You can accomplish it with the help of an automated php script. And I’m going to show you here exactly how to delete directory and all files and sub directories from it with php.
Delete All Files from Folder in PHP:
As for deleting all files from a folder the process is pretty straight forward. You only need two native php functions glob() and unlink() to achieve this.
- Function glob() returns an array of filenames/directories matching the given pattern.
- Function unlink() deletes a given file.
Our process goes like this — you have to loop through the files one by one from a given folder, check if it is a file and delete file with the help of unlink() function. Here is the simple php function I have written to delete all files from a directory.
PHP Function to Delete All Files from Folder:
Usage:
As you can see in function deleteFiles() we have used the pattern ‘/*’ to instruct glob() to get all the files names from the folder.
Next we loop through the files one by one and check if the item is a file and not a sub folder itself using is_file() function.
Once we confirm it as a file we delete it with unlink() method. The process will be repeated until no file is left in the specific folder.
Delete Only Particular File Type from Folder:
Say you don’t want to remove all files, just the pdf files alone from a folder. Then here’s the script for the task.
Delete Files Older than X Days from Folder:
This is another useful variation of the script. Suppose you want to delete older files say of at least 90 days old. You have to simply check if the last modified date and time of the file is greater than 90 days and delete if it is.
(60 * 60 * 24 * 90)) unlink($file); > > > ?>
To check if files are older than 90 days, we have used filemtime() to get last modified timestamp of a given file, took its difference from current timestamp and checked it against 90 days count.
Delete All Files and Sub Folders from a Folder in PHP:
So far we have seen about deleting just files present in a directory. What if you have sub directories with files inside the folder. In such case the above script won’t work. You’ll need to create recursive function to delete all files, sub-directories and parent directory altogether.
Simply deleting a folder with rmdir() won’t work. It will throw exception if you attempt to remove folder with files in it. So first you have to delete files one by one from each sub folder plus the rest of the files and then delete folders by removing parent folder.
Here is the php recursive function to delete files and sub folders from the folder.
Function Usage:
It will take care of deleting all files, sub folders from a folder automatically.
You can use the above php script to delete files and sub-directories in a given folder programmatically. The script is relatively fast but it depends on the amount of files and folders to be deleted. I hope you find this tutorial useful. Meet you in another interesting one 🙂