Delete All Files from Folder using PHP


delete-all-files-from-folder-php-codexworld

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.

In this short article, we’re going to write a simple PHP script to unlink or delete all files from folder or directory. There is no need to know the files name. To delete files from directory we’ll use glob() and unlink() functions in PHP.
glob() function is used to get filenames or directories as an array based on the specified pattern.
unlink() function is used to delete a file.

Here the PHP code is provided for three situations. In these situations, you should need to delete all files functionality in your web project.

Delete All Files from Folder:
The following script removes all files from the folder.

$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
}

Leave a reply

Connect With CodexWorld