Logging your visitor details to a text file

The ability to write a file in PHP make it easy to log visitor details to your site and can help website development.The HTTP_REFFERER variable holds the address of the web page which had the hyperlink which the user used to get to your page.

You can also see the users IP address using the REMOTE_ADDR variable which can be useful if you wish to block someone from your site.

They script below is an example of how you could log your visitors details.

<?php

//open up the log file
$file = fopen(‘log.html’, ‘a’);

//write the time of access

$time = date(‘H:i dS F’);
fwrite($file, ‘<b>Time:</b> $time<br/>’ );

//write the users IP address
fwrite( $file, ‘<b>Ip Address:</b> $REMOTE_ADDR<br/>’);

//write out the page that sent them here
fwrite($file, ‘<b>Referer:</b> $HTTP_REFFERER<br/>’);

//write the users browser details

fwrite( $file, ‘<b>Browser:</b> $HTTP_USER_AGENT<hr/>’);

//and finial, close the log file
fclose( $file );

?>

When you visit log.html you may get a page like below.

Time: 19:25 22nd December
Ip Address: 127.0.0.1
Referrer: http://webhostingchat.com/forums/index.php
Browser: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)


As you can see, the user was using Internet Explorer on Windows® XP®

Some browser do not recognize the HTTP_REFFERER header and it will not be shown.

This can be very useful to track the visitors to your site and too help you analyze the type ov visitors you are receiving.

*If you are using an Unix/Linux web server then you need to create a file name log.html and chmode it to 777

About the Author: James McMinn