I have a cron controller class that basically handles all cron job related work. I'm trying to add a function to the controller that deletes images that have been in the directory longer than a day. Here is what I have so far, and it makes sense to me I think, but when I test this to see if it works, I get errors such as:
Warning: filemtime(): stat failed for 4148_1432931936_0.jpeg
Warning: unlink(public/images/gallery_images/files/4148_1432931936_0.jpeg
public function delete_gallery_images()
{
$dir = opendir('../public/images/gallery_images/files/');
if ($dir) {
// Read directory contents
while (false !== ($file = readdir($dir))) {
if($file != "." && $file != "..") {
// Check the create time of each file (older than 1 day)
if (filemtime($file) < (time() - 60 * 60 * 24)) {
unlink('../public/images/gallery_images/files/'.$file);
}
}
}
}
// //close dir
// closedir($dir);
}
Any ideas? Thank you kindly.
Looks like you have inconsistent directory names. Try this:
public function delete_gallery_images()
{
$dirName = '../public/images/gallery_images/files/';
$dir = opendir($dirName);
if ($dir) {
// Read directory contents
while (false !== ($file = readdir($dir))) {
if($file != "." && $file != "..") {
// Check the create time of each file (older than 1 day)
$fname = $dirName . $file;
if (filemtime($fname) < (time() - 60 * 60 * 24)) {
unlink($fname);
}
}
}
}
//close dir
closedir($dir);
}