Page 1 of 1

Outputting images with PHP - no cache?

Posted: Fri Jan 05, 2007 1:57 pm
by Luke
I am using the following controller action to output my users's images, and when a user changes their image, (avatar) it will take around a second to switch... meaning if you go to the image, it shows the old one for around a second and then it gets switched to the new one... is this a cache issue? What causes this?

Code: Select all

public function imageAction()
    {
        $request = $this->getRequest();
        $get = new Zend_Filter_Input($request->getQuery());
        $id = $get->getDigits('id');
        // todo: move this into config table
        $dir = 'C:\\htdocs\\ChicoRotary\\upload\\';
        
        // Set photo defaults
        $photoType = 'image/gif';
        $photoPath = $dir . '\\unavailable.gif';
        
        if ($id)
        {
            $user = new Model_User;
            $user->loadId($id);
            $photo = $user->photo;
        }
        
        if (!empty($photo))
        {
            $photoPath = $dir . $photo;
            $image = new MC2_Image($photoPath);
            $photoType = $image->getType();
        }
        
        $response = $this->getResponse();
        $response->setHeader('Content-Type', $photoType);
        $response->setBody(readfile($photoPath));
    }

Posted: Fri Jan 05, 2007 4:54 pm
by feyd
Yes it's a caching issue. To overcome this you can generate a large, fairly high entropy textual string such as the result of md5() for the filename. Hopefully you will come up with a unique name more often than not. However you can also set the server to send a default life on those files of say one day.

Posted: Fri Jan 05, 2007 5:06 pm
by Luke
Oh... cool! All I had to do was change this...

Code: Select all

<img src="user/image?id=<?php echo $this->userId; ?>" width="80" height="80" />
to this...

Code: Select all

<img src="user/image?id=<?php echo $this->userId; ?>&hash=<?php echo md5(time()); ?>" width="80" height="80" />
I should have known to do that... I've only seen this question asked here about a million times. :oops:

Posted: Fri Jan 05, 2007 5:08 pm
by feyd
;)