Outputting images with PHP - no cache?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Outputting images with PHP - no cache?

Post 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));
    }
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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:
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

;)
Post Reply