Labels

php (34) javascript (30) phpjavascript (29) jquery (23) html (19) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Wednesday, January 24, 2018

Delete files from folder using php

Sometimes we need to free the space of the web server by deleting old or specific or all files from a directory. Means we want to remove files from the folder without know the name of the files. This type of functionality required for the following situation.
1. Need to remove all files in a folder for free the space of web server.
2. Need to remove old files in a folder which are used before the specific time.
3. Need to remove some files from a folder which holds a specific extension.

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.
Delete All Files from Folder:
The following script removes all files from the folder.
<?php
$files = glob('NewFolder/*'); //get all file names
// NewFolder is the name of folder
foreach($files as $file){   
 if(is_file($file))        
unlink($file); //delete file
}
?>
Delete Specific Type of file  from Folder:
The following script removes only those files which have a specific extension.(In this example delete all file with .jpg extension )
<?php
$files = glob('NewFolder/*.jpg'); //get all file names
// NewFolder is name of folder
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.
<?php
$files = glob('NewFolder/*'); //get all file names
// NewFolder is the name of folder
foreach($files as $file) {    
$lastModifiedTime = filemtime($file);    
$currentTime = time();    
$timeDiff = abs( $currentTime - $lastModifiedTime) / (60 * 60); //in one hours   
 if (is_file($file) &&  $timeDiff > 10) //check if file is modified before 10 hours     
 unlink($file); //delete file
}

No comments:

Post a Comment

More Posts

FOLLOW