Saturday, January 24, 2009

Log your blog visitors

So, you've got a shiny new blog out there on blogger and getting pretty many hits as well but want to keep a record of all people visiting your blog? Well, I do! Ever noticed the 'lens image with "Logged" written' here in the right panel of this blog? Yes, thats my own visitor logger. Although there are lots of third party loggers out there like the Wowzio widget but having your own is fun when you call yourself a techno-savvy! Ok, so here I go about it how to do it on your own.
Note: I'm assuming that you know how to use FTP, what is PHP and some other simple stuff etc... If you don't know these and don't understand the post, that means you're a n00b. I'm not going to explain everything in ultimate detail.
First things first
Here we're going to use PHP to track the visitors. So, you need a PHP capable server. Freehostia is cool for this task. Just register an account there.
1. Create an account on freehostia. Setup a subdomain like "" or something you wish there.
2. Create the image in mspaint or anything, that you wanna display to the user. Or if you're lazy then use the one from my blog. Name the image something like "img.jpg"
3. Create a PHP file with the following code and name it something like "logger.php":

$logged.="Time=".date("j/n/Y h:i:s a", time())."
foreach($_ENV as $key_name => $key_value) {
$logged.= $key_name . " = " . $key_value . "
$log2.="UA: ".getenv("HTTP_USER_AGENT")."
$log2.="IP: ".getenv("REMOTE_ADDR")."
$log2.="REFERRER: ".getenv("HTTP_REFERER")."
$blah=fopen("logdetails.htm", "a+");
fwrite($blah, $logged);

$blah2=fopen("log.htm", "a+");
fwrite($blah2, $log2);

$blah3=fopen("img.jpg", "rb+");
header("Content-type: image/jpg");
echo fread($blah3, 128);

4. Create two blank text files in notepad and rename them to "log.htm" and "logdetails.htm".
5. Now upload all these four files in the same directory in your freehostia account through FTP. chmod both the .htm files to 777.
6. Now in your blogger account, go to layout and add a new custom HTML/JS gadget. Add this code in it and place it where you wish on your blog
<img src="" alt="Logged"/>

Over!!! Yeah, it was that simple!!!
What happens under the hood???
If you've experience of coding, you might have already understood whats going on. But for those who are too lazy to want to understand I'm explaining briefly.
You've a PHP file on your freehostia which when accessed performs two things:
1. Shows the user an image i.e. the logged image
2. Records all environment variables and the values and writes to the file logdetails.htm and the file log.htm is to store Time, UA and IP only for your quick viewing.

Whenever anyone visits your blog, his/her browser requests for the image. The request reaches your freehostia account alongwith headers sent by the browser. The headers are trapped by the PHP script which shows an image to the user. Thats it! As simple as that!!!

No comments: