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.
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 hoursif (is_file($file) && $timeDiff > 10) //check if file is modified before 10 hoursunlink($file); //delete file}
No comments:
Post a Comment