Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Track your visitors, using PHP (http://www.go4expert.com/articles/track-visitors-using-php-t195/)

Kings 15Nov2004 03:14

Track your visitors, using PHP
There are many different traffic analysis tools, ranging from simple counters to complete traffic analyzers. Although there are some free ones, most of them come with a price tag. Why not do it yourself? With PHP, you can easily create a log file within minutes. In this article I will show you how!

Getting the information
The most important part is getting the information from your visitor. Thankfully, this is extremely easy to do in PHP (or any other scripting language for that matter). PHP has a special global variable called $_SERVER which contains several environment variables, including information about your visitor. To get all the information you want, simply use the following code:
PHP Code:

// Getting the information
$ipaddress $_SERVER['REMOTE_ADDR'];
$page "http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}"
$page .= iif(!empty($_SERVER['QUERY_STRING']), "?{$_SERVER['QUERY_STRING']}""");
$referrer $_SERVER['HTTP_REFERER'];
$datetime mktime();
$useragent $_SERVER['HTTP_USER_AGENT'];
$remotehost = @getHostByAddr($ipaddress); 

As you can see the majority of information comes from the $_SERVER variable. The mktime() and getHostByAddr() functions are used to get additional information about the visitor.

Note: I used a function in the above example called iif(). You can get this function at http://www.phpit.net/code/iif-function.

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 and 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.
PHP Code:

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

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

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

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

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:
PHP Code:

include ('log.php'); 

Okay, now I want to view my log file
After a while you'll probably want to view your log file. You can easily do so by simply using a standard text editor (like Notepad on Windows) to open the log file, but this is far from desired, because it's in a hard-to-read format.

Let's use PHP to generate useful overviews for is. The first thing that needs to be done is get the contents from the log file in a variable, like so:
PHP Code:

// Open log file
$logfile "/some/path/to/your/logfile.txt";

if (
file_exists($logfile)) {
$handle fopen($logfile"r");
$log fread($handlefilesize($logfile));
} else {
    die (
"The log file doesn't exist!");

Now that the log file is in a variable, it's best if each logline is in a separate variable. We can do this using the explode() function, like so:
PHP Code:

// Seperate each logline
$log explode("\n"trim($log)); 

After that it may be useful to get each part of each logline in a separate variable. This can be done by looping through each logline, and using explode again:
PHP Code:

// Seperate each part in each logline
for ($i 0$i count($log); $i++) {
$log[$i] = trim($log[$i]);
$log[$i] = explode('|'$log[$i]);

Now the complete log file has been parsed, and we're ready to start generating some interesting stuff.

The first thing that is very easy to do is getting the number of pageviews. Simply use count() on the $log array, and there you have it;
PHP Code:

echo count($log) . " people have visited this website."

You can also generate a complete overview of your log file, using a simple foreach loop and tables. For example:
PHP Code:

// Show a table of the logfile
echo '<table>';
'<th>IP Address</th>';
'<th>Remote Host</th>';

foreach (
$log as $logline) {

'<td>' $logline['0'] . '</td>';
'<td>' urldecode($logline['1']) . '</td>';
'<td>' date('d/m/Y'$logline['2']) . '</td>';
'<td>' $logline['3'] . '</td>';
'<td>' $logline['4'] . '</td>';




You can also use custom functions to filter out search engines and crawlers. Or create graphs using PHP/SWF Charts. The possibilities are endless, and you can do all kinds of things!

In Conclusion...
In this article I have shown you have to create a logging module for your own PHP website, using nothing more than PHP and its built-in functions. To view the log file you need to parse it using PHP, and then display it in whatever way you like. It is up to you to create a kick-*** traffic analyzer.

If you still prefer to use a pre-built traffic analyzer, have a look at http://www.hotscripts.com.

shabbir 15Nov2004 17:03

Re: Track your visitors, using PHP
Nice way to log the visitors and track them but I find the best method to store the log in database if you are using PHP to retrieve the same and display it. Writing to a file can be used by other parties to see what you may not want to display also.

Shabbir Bhimani

Kings 16Nov2004 01:58

Re: Track your visitors, using PHP
I agree with you, but it's not always possible to store them in a database (e.g. when you don't have MySQL available).

shabbir 16Nov2004 09:17

Re: Track your visitors, using PHP

Originally Posted by Kings
I agree with you, but it's not always possible to store them in a database (e.g. when you don't have MySQL available).

Thats true but I guess any hosting provider or seeker having php without MySQL cannot be thought of. If thats the case then PHP is not anything above HTML. I meant from dynamic content point of view.

coderzone 16Nov2004 09:20

Re: Track your visitors, using PHP
I must say a nice tip for PHP beginners.

go4expert 16Nov2004 09:21

Re: Track your visitors, using PHP
Really Impressive Kings. Dont mind having something like this more than just this one.

BlasterBlang 13Nov2006 18:22

Re: Track your visitors, using PHP
Nice Post.......i got great help frm you for my visitor tracking

shabbir 14Nov2006 10:28

Re: Track your visitors, using PHP
BlasterBlang, Confine links to signatures only

manilodisan 11Dec2006 02:53

Re: Track your visitors, using PHP
I will recommend this one to my visitors

CoastPlumbing 18May2011 04:29

Re: Track your visitors, using PHP
Fantastic article this is very helpful. I have currently implemented this on my site and is working.

A couple of questions though:

1. How can you add a time stamp to each IP logged.
2. Is there a way to include the geographic location of a visitor.
3. How would you implement tracking a visitors movements throughout the site.

Thanks :happy:

All times are GMT +5.5. The time now is 22:44.