How to know when to look for a new image?

advertisements

I have a copy of 350+ images on my sever, when a person tries to view one, if it is more than 5 minutes old, I want my sever to check with another website that I am mirroring data from(they insist on me mirroring instead of hotlinking) and get the newest copy. Any thoughts on how to do this?

I can do a cron script and get all of the images, but there are problems doing that.(My host limits me to once every 15 minutes, I would have to get a lot of images that my users may or may not actually view.)

I am thinking there should be a way to do this in PHP, but I have no idea where I would start.


You could serve the images via a php script that allows you to do the necessary checks before displaying the image.

<img src="/index.php/image-name.jpg">

Below is one option for the checks

// get the image name from the uri
$image = explode("/", $_SERVER['REQUEST_URI'])[2];
// check if the image exists
if (is_file($image)) {
    // get the file age
    $age = filemtime($image);
    if ($age < time() - (60*5)) { // 5 mins old
        // file too old so check for new one
            // do your check and serve the appropriate image
    }
    else
    {
        // get the image and serve it to the user
        $fp = fopen($image, 'rb');
        // send the right headers
        header("Content-Type: image/jpg");
        header("Content-Length: " . filesize($image));
        // dump the picture and stop the script
        fpassthru($fp);
        exit();
    }
}
else
{
    // handle error
}