Most efficient way to display a 1x1 GIF (tracking pixel, web beacon) Most efficient way to display a 1x1 GIF (tracking pixel, web beacon) javascript javascript

Most efficient way to display a 1x1 GIF (tracking pixel, web beacon)


maybe

header('Content-Type: image/gif');//equivalent to readfile('pixel.gif')echo "\x47\x49\x46\x38\x37\x61\x1\x0\x1\x0\x80\x0\x0\xfc\x6a\x6c\x0\x0\x0\x2c\x0\x0\x0\x0\x1\x0\x1\x0\x0\x2\x2\x44\x1\x0\x3b";

That will output a binary string identical to the binary file contents of a 1x1 transparent gif. I'm claiming this as efficient based on the grounds that it doesn't do any slow IO such as reading a file, nor do I call any functions.

If you want to make your own version of the above hex string, perhaps so that you can change the color, you can use this to generate the php code for the echo statement.

printf('echo "%s";', preg_replace_callback('/./s', function ($matches) {    return '\x' . dechex(ord($matches[0]));}, file_get_contents('https://upload.wikimedia.org/wikipedia/en/d/d0/Clear.gif')));


   header('Content-Type: image/gif');    header("Content-Length: " . filesize("image.gif"));   $f = fopen('image.gif', 'rb');   fpassthru($f);   fclose($f);

Probably would be fastest for image from disk, but (especially if you're using bytecode caching) for a small images known in advance the base64 way will be the fastest I think. Sending Content-Length might be a good idea too, for the small image the browser would in most cases not wait for anything after receiving the bytes so while your server would take as much time, use experience will be sightly better.

Another way would be to let Apache/lighttpd/nginx serve the image, log the access and the parse it offline.


With Laravel:

$pixel = "\x47\x49\x46\x38\x39\x61\x1\x0\x1\x0\x80\x0\x0\xff\xff\xff\x0\x0\x0\x21\xf9\x4\x1\x0\x0\x0\x0\x2c\x0\x0\x0\x0\x1\x0\x1\x0\x0\x2\x2\x44\x1\x0\x3b";return response($pixel,200,[    'Content-Type' => 'image/gif',    'Content-Length' => strlen($pixel),]);

If anyone wants that for some reason.

Alternatively, if you don't like long(ish) hex strings in your code:

base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw')