PHP Tutorials

XMLStyleSoldierFlowerMonkey

Simple User Log

A simple user log can help you keep track of who's been visiting your site and where they are coming from.

Spreadshirt
Alright, this is a simple little script which tells when the file was last modified using the PHP filemtime() function. The user log we are going to make will be stored on a flat file, meaning it doesn't require any databases like mySQL. It will store four basic functions:
  1. The time the user came to the page.
  2. The IP address of the user.
  3. The referer of the user, if there is one.
  4. What browser he was using.
All of those four functions are built into PHP, so we will not have much work to do. All we have to do is define these functions, and then send them to a log HTML file. First, you will need to create a log.html and CHMOD it to 777, setting all permissions to the file. We will use the date() function to set the time. The rest of the other variables are all predefined in PHP. The second part of the script will open up log.html using the fopen() and write all the data in using fputs(). Here is the PHP, the comments should help you out:
<?

//using the date() function
$time = date("F jS Y, h:iA"); 

//$remote_addr is PHP variable to get ip address
$ip = $REMOTE_ADDR;  

//$http_referer is PHP variable to get referer
$referer = $HTTP_REFERER;  

//$http_user_agent is PHP variable for browser
$browser = $HTTP_USER_AGENT;  

//what page they came from
$page = $_SERVER['REQUEST_URI'];

//use the fopen() function
$fp = fopen("log.html",  "a");  

//using the fputs() function
fputs($fp, "
Time: $time
IP: $ip
Referer: $referer
Browser: $browser
Page: $page
");
  
fclose($fp);  

?>
And that is basically all the code we have to write to set up a simple user log. You can place this code anywhere on your main page, and it will do the rest. Remember to make a blank log.html page, upload it to your server in the same directory as the page where the code will be located, and CHMOD it 777. Well thats it folks. I hope it works out for you and if it doesn't you can post a question.

Discuss this tutorial »
Written by: Akash Goel
Back to PHP TutorialsTop


Copyright © 2000-2008 Spoono, LLC. All rights reserved.
Network: Reseller Web Hosting by Spoono Host | Spoonloads | Absolute Cross
Terms of Service | Privacy Policy.

kdfj