Helping ordinary people create extraordinary websites!

Track Your Visitors, Using PHP

By Dennis Pallett
2005-05-26

Logging the information

Now that you have all the information you need, it must be written to a log file so you can later look at it, and create useful graphs and charts. To do this you need a few simple PHP function, like fopen (http://www.php.net/fopen) and fwrite (http://www.php.net/fwrite).

The below code will first create a complete line out of all the information. Then it will open the log file in "Append" mode, and if it doesn't exist yet, create it.

If no errors have occurred, it will write the new logline to the log file, at the bottom, and finally close the log file again.


// Create log line
$logline = $ipaddress . '|' . $referrer . '|' . $datetime . '|' . $useragent .
'|' . $remotehost . '|' . $page . "
";

// Write to log file:
$logfile = '/some/path/to/your/logfile.txt';

// Open the log file in "Append" mode
if (!$handle = fopen($logfile, 'a+')) {
die("Failed to open log file");
}

// Write $logline to our logfile.
if (fwrite($handle, $logline) === FALSE) {
die("Failed to write to log file");
}

fclose($handle);


Now you've got a fully function logging module. To start tracking visitors on your website simply include the logging module into your pages with the include() function (http://www.php.net/include):


include ('log.php');




Tutorial pages:
 1 Votes

You might also want to check these out:


Leave a Comment on "Track Your Visitors, Using PHP"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS