Log visitors to file

Author: Mattias (mattias@999tutorials.com)
Categories: PHP
 It's nice to know how many visitors your site gets. To get you started I show you how to log statistics of all your visitors, in a simple way. The log will be saved in a text file.
The tutorial:

Digg this, Post to del.icio.us,

Do you know how many visitors you get to your site every day, and where they come from? Why not log it your self with this pretty simple technique and save the statistics to a plain file of the web server.

There are many different ways to save statistics. And many of them save TO much information. I will start you up with a solution that save only unique visitors, where they come from, when and what page they looked at.

Q: So how can we know if the visitor is new to the site?

A: Start a session for all visitors. All visitors without a session are new :-)

Enough talking alright... Here comes the PHP code:

session_start();
if($_SESSION["logged"] != "yes")
{
$agent = $_SERVER['HTTP_USER_AGENT'];
$uri = $_SERVER['REQUEST_URI'];
$ip = $_SERVER['REMOTE_ADDR'];
$ref = $_SERVER['HTTP_REFERER'];
$visitTime = date("r"); //Example: Thu, 21 Dec 2000 16:01:07 +0200


$logLine = "$visitTime - IP: $ip || User Agent: $agent || Page: $uri || Referrer: $ref\n";
$fp = fopen("visitorLog.txt", "a");
fputs($fp, $entry_line);
fclose($fp);
$_SESSION["logged"] = "yes";
}
?>

 

The code is pretty streight forward. But some explanation might be handy.

First we start a session. Check if the session variable "logged" is NOT "yes". In that case we have a new visitor. Use the PHP variable $_SESSION and get all interesting data about the request and the user. I choose "Useragent", "uri" (what page is accessed), ip (Visitors IP address), ref (What page did the user find your site through?)

After that we build the row we want to save to our log file.
fopen() opens a file in append mode (creates if not there, otherwise append to existing at the bottom)

Make sure the directory/file is writable for the web server. SECURITY: it might be smart to put the log file out of the web root, so you don't need to set write access in your root and that people can see your stats.

fputs() writes the row in the file and fclose... closes the file :-) Surprise....

Last we set the session variable logged to "yes" so we know that we don't need to log the visitor next page he looks at.

Next week I will create a tutorial about how to add similiar information to a database and show nice stats... so stay tuned!

Share this tutorial
 


Digg this, Post to del.icio.us,
 


eXTReMe Tracker