Reputation: 381
I'm developing a web service in php
which generates images using an external application. After generating the image file is inserted into the html page. Like this:
<img src="img/52454879c7158.png">
After viewing the file, it is no longer needed. But in the end in a folder with pictures accumulate a large number of files. How can I automate the deletion of files?
Upvotes: 1
Views: 253
Reputation: 3045
You should periodically delete files in a specific directory the unix program find comes to the rescue. In your specific case you needed to delete all the image files from a img folder that where older than 1 days.
This is the crontab entry to accomplish that:
Command is
crontab -l
Linux Crontab Format
MIN HOUR DOM MON DOW CMD
0 0 * * * /usr/bin/find /yourpathto/img/ -type f -name '*.png' -mtime +1 -exec rm {} \;
(everything in one line)
The code runs the program /usr/bin/find
every day at midnight (0 0 * * *)
.
It checks the directory called /yourpathto/img
for everything that is a file (-type f
),
has a name that ends in .png (-name '*.png') and is created 1 days ago or before that (-mtime +1
).
The command then executes rm (remove) on all those files (-exec rm {} \;)
.
Or, You can use the *.*
to remove all the files inside /yourpathto/img/*.*
after setting-up the crontab it is automatically run and remove all the files from your /yourpathto/img/
directory.
Alternate Option to delete files:
function removeall()
{
$files = glob('path/to/img/*'); // get all file names
foreach($files as $file){ // iterate files
// Here you should make one condition that if user has view / download this file and remove it
if(is_file($file))
unlink($file); // delete file
}
}
Here you should apply something that if user has download file than this function will be call to remove files.
Upvotes: 1
Reputation: 4620
delete time just use unlink
unlink(folder/filename);
Example
unlink("folder/images/image_name.jpeg");
Show Image after delete image using php
$imageUrl = "/images/123.jpg"; // link to image
$imginfo = getimagesize($imageUrl); // get mime info
header("Content-type: " . $imginfo['mime']); // add Content-type header
readfile($imageUrl); // show image
unlink($imageUrl); // delete image
Upvotes: 1