PHP Web Bug - Transparent gif Tracking


A Web bug, or tracking beacon is usually a 1x1 transparent gif (the smallest possible image), which is embedded into webpages or emails that support images. When the webpage is viewed, the browser sends an http request to fetch the image. The request is mapped to a script which is executed and can store user information like ip address and access time on the server. The web server requested an image and not a script after all, so the last line of the script usually outputs a 1x1 transparent image so the user will never notice it.

Many webmail programs like gmail will not automatically display images embedded into email to prevent web bug email tracking in email and spam.

Some examples use the gd2 php extension, which is inefficient. It takes a lot of overhead to load the extension and allocate an image. For scalability reasons, it is better to hard code the 1x1 transparent image so the image is not needlessly generated on the fly.
example:
<img src="webbug.php" width="1" height="1" />

webbug.php
<?php
//do whatever processing here....
//example: save ip address and timestamp
$str=date("Y-m-d H:i:s") . ": ". $_SERVER['REMOTE_ADDR'] . "\n";
$temp_file = tempnam(sys_get_temp_dir(), 'ip_list');
file_put_contents($temp_file, $str, FILE_APPEND);
 
header("content-type: image/gif");
//43byte 1x1 transparent pixel gif
echo base64_decode("R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
?>

code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)

andy on 2009-03-19 01:28:39
this doesn't work. in firefox you get the messed up image symbol.

eugene on 2009-07-09 06:47:59
This works fine on FF3.5
could also try dataURI instead of base64.
http://en.wikipedia.org/wiki/Data_URI_scheme

but not compatible on older browsers like IE.