Recommended sites
Web Hosting Reviews

Creating a file based logging script

Creating a file based logging script

In this tutorial I will show you how you can create a small and simple PHP script to log your visitors activity into a file. You just need to add 1 line to each of your page to enable logging and the statistics will be collected in a html file so you don't have to setup any database for this task.

Step 1.
A basic logging script need to log visitors information in an easy and well-arranged format. In general the site owner want to know which pages of his/her site were visited most often, what source was the referrer and so on.

In this tutorial we will collect the following information about the visitor:

  • Visiting date
  • Visitor IP
  • Visitor hostname
  • Visitor browser type
  • The visited page
  • The referrer to the page

From this information you can the site owner can make any decision how to improve the site.


Step 2.
Now it's time to make some coding as well. To get the visitors IP, browser, referrer and visited page we can use the PHP built in super global variable the $_SERVER. From this array we can read out the above mentioned properties and their values.

So the code is the following:

<?php
    $userAgent 
= ( isset($_SERVER['HTTP_USER_AGENT']) 
                     && (
$_SERVER['HTTP_USER_AGENT'] != "")) 
                 ? 
$_SERVER['HTTP_USER_AGENT'] : "Unknown";
                 
    
$userIp    = ( isset($_SERVER['REMOTE_ADDR']) 
                      && (
$_SERVER['REMOTE_ADDR'] != ""))     
                  ? 
$_SERVER['REMOTE_ADDR']     : "Unknown";
                  
    
$refferer  = ( isset($_SERVER['HTTP_REFERER']) 
                     && (
$_SERVER['HTTP_REFERER'] != ""))
                 ? 
$_SERVER['HTTP_REFERER']    : "Unknown";
                 
    
$uri       = ( isset($_SERVER['REQUEST_URI'])
                      && (
$_SERVER['REQUEST_URI'] != ""))
                  ? 
$_SERVER['REQUEST_URI']     : "Unknown";

?>


Explanation:
The $_SERVER array key definition are the following:

HTTP_USER_AGENT : Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586).

REMOTE_ADDR: The IP address from which the user is viewing the current page.

HTTP_REFERER:
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

REQUEST_URI: The URI which was given in order to access this page; for instance, '/index.html'.

So we try to read this information if the actual properties doesn't exists or empty than we set it to 'Unknown'.

To get the hostname from the userIp I use the PHP built in function gethostbyaddr() which gets the Internet host name corresponding to a given IP address. Besides this getting the actual date is quite easy by using the date() function with a predefined date format string.

This part of the code looks like this:

<?php
    define
("DATE_FORMAT","d-m-Y H:i:s");

    
$hostName   = gethostbyaddr($userIp);
    
$actualTime = date(DATE_FORMAT);
?>


Step 3.
Now as we have the all of the visitors information so we need to store it in a file. To make it easier to read the file I will surround the data with a HTML table elements. As result when you open the log file you will get all of the information in a nice formatted HTML table.

The code which composes a log entry looks like this:

<?php
    $logEntry 
= " <tr>
        <td>$actualTime</td>
        <td>$userIp</td>
        <td>$hostName</td>
        <td>$userAgent</td>
        <td>$uri</td>
        <td>$refferer</td>
    </tr>\n"
;
?>


Now we have to make some file handling. First of all we need to check whether the log file exists or not. If the file not exists yet than we will create a new one and write some HTML header information at the beginning. If the file already exists than we open it to append a new log entry.
After it we can write the log entry to the file and close it afterwards. That's all. As the file is a html file you can easy open/display it.

The complete logger coode looks like this:

<?php
    define
("DATE_FORMAT","d-m-Y H:i:s");
    
define("LOG_FILE","visitors.html");

    
$logfileHeader='
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<head>
   <title>Visitors log</title>
</head>
<body>
  <table cellpadding="0" cellspacing="1" border="1">
    <tr>
      <th>DATE</th>
      <th>IP</th>
      <th>HOSTNAME</th>
      <th>BROWSER</th>
      <th>URI</th>
      <th>REFERRER</th></tr>'
."\n";

    
$userAgent = ( isset($_SERVER['HTTP_USER_AGENT']) 
                     && (
$_SERVER['HTTP_USER_AGENT'] != "")) 
                 ? 
$_SERVER['HTTP_USER_AGENT'] : "Unknown";
                 
    
$userIp    = ( isset($_SERVER['REMOTE_ADDR']) 
                      && (
$_SERVER['REMOTE_ADDR'] != ""))     
                  ? 
$_SERVER['REMOTE_ADDR']     : "Unknown";
                  
    
$refferer  = ( isset($_SERVER['HTTP_REFERER']) 
                     && (
$_SERVER['HTTP_REFERER'] != ""))
                 ? 
$_SERVER['HTTP_REFERER']    : "Unknown";
                 
    
$uri       = ( isset($_SERVER['REQUEST_URI'])
                      && (
$_SERVER['REQUEST_URI'] != ""))
                  ? 
$_SERVER['REQUEST_URI']     : "Unknown";

    
$hostName   = gethostbyaddr($userIp);
    
$actualTime = date(DATE_FORMAT);

    
$logEntry = " <tr>
        <td>$actualTime</td>
        <td>$userIp</td>
        <td>$hostName</td>
        <td>$userAgent</td>
        <td>$uri</td>
        <td>$refferer</td>
    </tr>\n"
;

    if (!
file_exists(LOG_FILE)) {
        
$logFile = fopen(LOG_FILE,"w");
        
fwrite($logFile, $logfileHeader);
    }
    else {
        
$logFile = fopen(LOG_FILE,"a");
    }

    
fwrite($logFile,$logEntry);
    
fclose($logFile);
?>


Step 4.
Using the logger script is quite easy. Each of your page you want to log you need to add a new line: require_once("logger.php");
If the page is not a Php page than you need to rename it from html to Php or tell the Php to interpret the *.html pages as well.

So an example file looks like this:

<?php
    
require_once("logger.php");

    echo 
"<h3>This is an example page to show you how to use logger.</h3>";
    echo 
"Just insert the following code into your files:<br/>";
    echo 
'require_once("logger.php");';
?>


You can download a complete logging system as well.

Sponsored links