Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP URL string to avoid browser caching

Tags:

php

caching

My site is designed to be a funny picture site, when the user hits the random button a PHP code on the same page generates a new random picture, this is how it is supposed to work. I however have to hit the F5 button to get a new image.

I was reading on another question that people use a get date and get time query string generated at the end of the link to avoid browser caching, I however can not figure it out for the life of me.

I am not very good with php so please speak as if I only know the basic webpage structure. Thank you!

like image 728
Clayton Moss Avatar asked Dec 18 '12 19:12

Clayton Moss


People also ask

How do I stop browser caching the page in PHP?

You can avoid this problem by using private_no_expire mode. The Expire header is never sent to the client in this mode. Setting the cache limiter to '' will turn off automatic sending of cache headers entirely. The cache limiter is reset to the default value stored in session.

How do I stop my browser from caching?

When you're in Google Chrome, click on View, then select Developer, then Developer Tools. Alternatively, you can right click on a page in Chrome, then click Inspect. Click on the Network tab, then check the box to Disable cache. You can then close out of Developer Tools.

Do browsers cache PHP files?

I came to the conclusion that, by default, php files are never EVER pulled from cache, even in mobile browsers, even if in the response there is no Cache-Control nor Expires parameter, even if i don't send POST requests and i just follow a link to the page. They are always redownloaded.


1 Answers

What you are describing is called a cache breaker and is usually a random string or a timestamp appended to the url. When you are referencing your image, prepend it like this:

echo get_random_image_url() . '?' . time();

This will result in an url looking like this:

http://your.server.com/random.jpg?1355862360

Note: get_random_image_url is just an example, but i'm sure you get the idea.

This thread may be of interest: How to force a web browser NOT to cache images.

like image 184
alexn Avatar answered Sep 24 '22 11:09

alexn