enenen
enenen

Reputation: 1967

How to detect if the browser requests a certain file from the server

Can I detect if the web browser is requesting a certain image from the server? I want to check if the user downloads the image or if it is already cached from its browser.

The main idea:

I am counting unique visitors per profile page. I use IPs and Cookies for now but want to add this, too. IP could be changed easily, Cookie could be blocked/deleted. My idea is to use this information just like a flash cookie. The image will be 1px x 1px in size and will be invisible to the user. I don't have experience with ActionScript and Flash at all, so I can't use flash cookie and want to try with this.

EDIT: As I understand from Sven's answer maybe I couldn't explain what I need. My question is same as Sven's answer. How to wait for the request to appear on the server? I want the browser to cache the image, so it will be downloaded only if the user is an unique visitor, i.e. he is viewing the page for the very first time.

I want to get this information and check if the image is requested or not (i.e. it is cached). Something like:

$requested_files = $_SERVER['REQUESTS']; // Or something similar, this is the question.
$file_name = $profile_page_owner_id.'.png'; // For example.

if(in_array($file_name, $requested_files)) {
    // File is requested, so it is not cached. This is an unique visitor.
    // Of course except this I will continue to check IP and Cookie.
    // This will be the 3rd check.
} else {
    // File is not requested, so it is already cached.
    // Page is viewed before, this is not an unique visitor.
}

Upvotes: 3

Views: 1396

Answers (3)

Sven
Sven

Reputation: 70853

You can detect it by simply waiting for the request to appear on the server.

If you get a request, the browser has not cached it.

If you do not want the browser to cache it, simply say so in the http headers. Then you'll get the request every time.

Edit: Ok, if you WANT caching of the image, simply send cache headers that allow for indefinite caching in the browser. Usually the image will then be requested only once. The detection of the request stays the same.

Upvotes: 0

Just create a PHP file that will output an image, add the logics you need (counting and stuff) before the output, call the php file in an html image and force the image to be cached by sending a header like header('Cache-Control: max-age=37739520, public');

You can take a look at this post: How to get the browser to cache images, with php? for more information about caching.

Upvotes: 1

Madara's Ghost
Madara's Ghost

Reputation: 174957

Have your image path set to, let's say user_track.php, the browser will request the file, where you do your logging, then send the appropriate headers and the image itself.

You can even send cache-denial headers, so that the image won't be cached by default.

Upvotes: 1

Related Questions