缓存1个多域的文件

First of all, I'm sorry about the title. I couldn't find a better one.

I've a image file, generated by a PHP script. this script (image) is connected to a database and saves its referrer url in a table. Because the output image doesn't change, I think it's better to cache it.

But as I know, if I cache 1 file (for example http://www.example.com/img.png.php), on every pages, the browsers reads it from cache. and it's not good for my script. because on the first call, it save the referrer url and cached by browser. And on the next calls, on different websites (referrers), cached version will be used and browser don't send any request to the server, and finally referrer url won't save in the database.

Can I say to browser, please cache 1 copy of the image for each domain? I mean:

http://wwww.abc.com/index.html sends a request to get my image (script)

browser checks its cache, and doesn't find it. so get it from the server. and PHP script saves the referrer url.

the user goes to another page of ABC.COM. (for example: http://wwww.abc.com/about.html) browser check the cache, it finds it. so doesn't send a request to the server to get the file content. and PHP script won't run.

another site (http://wwww.efg.com/index.html) sends a request to get my image (script) browser checks cache, and WILL NOT find it. so send a request for file content. and PHP script runs...............................

Is it possible? (sorry for long text, with a lots of grammatical problems)

You could use a redirect page (that is not cached) that saves the referrer to your database and then redirects to the cached image.

That way you always get a hit but the actual image is cached.


In your HTML you could use:
<img src="/image.php">

And in image.php:

<?php
    // save the referrer in here

    header('Location: /image.jpg');
?>

and /image.jpg is your actual image (which can be cached)

Seems to be a counter, am I right?

AFAIK you cannot do exactly what you've explained.

But you always can "cache" an image on the server side so you wouldn't need to redraw it:

<?
/*
  do some stuff
*/
// send an image: the content-type first
header('Content-type: image/png');
// and the image
readfile('myImage.png');

First of all, think about the user's experience: Do you really need to increase page load time just for the referrer feature? Also, you should be aware that many browser/privacy tool configurations suppress or don't send the Referer header in the first place.

If you're really sure that you want the resource(JavaScript, stylesheet, image, ...) to load each time, you can send the Cache-Control HTTP header with the resource to prevent caching. For example, to prevent caching of referer.js when served with Apache, add the following .htaccess file in the same directory (requires mod_header):

<FilesMatch "^referer\.js$">
Header set Cache-Control no-cache
</FilesMatch>