- 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
- Php unlink all file in directory
- PHP: Delete all files from a folder.
- Deleting files in sub-folders.
- Delete All Files from Folder using PHP
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
Php unlink all file in directory
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
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.
Delete All Files from Folder using PHP
Sometimes you need to free the space of the web server by deleting old or specific or all files from a directory. Means you want to remove files from the folder without know the name of the files. This type of functionality required for the following situation.
- Need to remove all files in a folder for free the space of web server.
- Need to remove old files in a folder which are used before the specific time.
- Need to remove some files from a folder which holds a specific extension.
- And much more.
$files = glob('my_folder/*'); //get all file names
foreach($files as $file) if(is_file($file))
unlink($file); //delete file
>
Delete All Files of Specific Type Recursively from Folder:
The following script removes only those files which have a specific extension.
$files = glob('my_folder/*.jpg'); //get all file names
foreach($files as $file) if(is_file($file))
unlink($file); //delete file
>
Delete Old Files from Folder:
The following script removes the files which modified before the specified time.
$files = glob('my_folder/*'); //get all file names
foreach($files as $file) $lastModifiedTime = filemtime($file);
$currentTime = time();
$timeDiff = abs($currentTime - $lastModifiedTime)/(60*60); //in hours
if(is_file($file) && $timeDiff > 10) //check if file is modified before 10 hours
unlink($file); //delete file
>
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question