Random Favicons (the advanced way)

Isn't it neat if every time the same person visits your website he will get a totally fresh and new favicon? Just that is a reason to visit your website again and again! oh well maybe not.

To follow this tutorial you need to know how to, at least, USE favicons. So let's start.

Say you have 3 favicons, name them favicon2.ico, favicon3.ico and favicon4.ico. You must use numbers like this, you'll see why later. Put them in your home directory.

Create a new php file named favicon.php. Add this code into it, and edit it if you need.

<?php
$number = mt_rand(2,4);
header('Content-type: image/x-icon');
readfile ($_SERVER['DOCUMENT_ROOT'] . "/favicon" . $number . ".ico");
?>

$number = mt_rand(2,4); will make a random number 2, 3 or 4, and put it in a variable. (If you use a php version prior to 4.2.0, you need to seed the number generator first. Click on the mt_rand link in the code above to read more.)

header('Content-type: image/x-icon'); tells the server to set header to image/x-icon. This will make browsers understand it's an icon the server is sending. (You can do this with the correct mime type to send e.g video files or anything else.

readfile ($_SERVER['DOCUMENT_ROOT'] . "/favicon" . $number . ".ico"); reads the binary data of the randomized icon file and outputs it to the browser. $_SERVER['DOCUMENT_ROOT'] is a preset variable I love. It will get the full server path to your web directory e.g /home/users/username/apache/htdocs or whatever it could look like on the server. The whole line here will make up something like /home/users/username/apache/htdocs/favicon3.ico.

** OPTIONAL PART STARTS HERE **
I think this will cause better performance somehow. Your web host must support .htaccess or you must have access to apaches main config for doing this one. Rename your favicon.php to favicon.ico. So now we have to make the web server still understand it's a php file.

Create a text file and name it .htaccess if you don't have it already, could be tricky to name it to that on a windows machine, if so, rename it after you have uploaded it to your server. Insert this code into it:

addType application/x-httpd-php .ico

This will simply make apache handle .ico files as php.
** END OF OPTIONAL PART **

Then use this html code in the body tag as usual:

<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Or if you just named it favicon.php, then of course use that name. Got any problems? Just contact me.

Comments

Written by Leo | Sun, 27 Aug 2006, 01:04

That's cool, thanks!

Leave a comment

CAPTCHA image (Click the image to get a new one)