The simple trick here is to make the browser think that the image file is new. Most web professionals know that browsers will cache and image and remember it’s url and then if you try to access that url again it will show you the image you already downloaded rather than getting a new copy form the server every time. This is great and helps us surf the web faster overall. Sometimes this can bite us though, specifically when you are trying to show someone an image which you just updated and all they see is the old one. If you are in the business of creating things online and having them approved online, you could run into this situation multiple times before lunch every day. Raise your hand if you’ve had to walk a client though how to clear their cache, fun times right? One more situation when this is helpful is I’ve noticed some browsers (firefox) caching animated gifs, and they will not replay the animation if you refresh the page. But for banners and such sometimes you will want the animated gif to replay on reloading the page. I’ve started using this little trick to keep my pages from caching the images and saving me and clients confusion.
So the browser remembers the url and if you try to get that same url later, it will just display what you’ve already downloaded. The trick is to make the browser think it’s a new url. You can do this pretty easily by adding a query string to the end of the url. Those are the urls that have the file name and then it’s followed by a ‘?’ and some jibberish, for example: my-image-i-dont-want-cached.jpg?version=something. This will work once, but the real trick is to have a unique query string every time. I’ve seen this done with random numbers and a number of other things, but my favorite is to add the date to the url. With the date you know that it will always be unique (as it includes seconds).
As long as you understand what cache is and why it’s a good thing to have in most scenarios and you are in one of those exceptions where it’s best not o have it, here’s how to do it.
if (image.src.indexOf("?") == -1)
image.src = image.src + "?v=" + Date();
<div class="container"><p>PHP append to img src</p><img src="160x600.gif?v=<?php echo Date("Y.m.d.G.i.s")?>" width="160" height="600" border="0" /></div>