Track your visitors, using PHP
(Page 3 out of 4)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:
$logfile = '/some/path/to/your/logfile.txt';
if (file_exists($logfile)) {
$handle = fopen($logfile, "r");
$log = fread($handle, filesize($logfile));
fclose($handle);
} 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:
$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:
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;
You can also generate a complete overview of your log file, using a simple foreach loop and tables. For example:
echo '
IP Address | ';Referrer | ';Date | ';Useragent | ';Remote Host | ';
---|---|---|---|---|
' . $logline['0'] . ' | ';' . urldecode($logline['1']) . ' | ';' . date('d/m/Y', $logline['2']) . ' | ';' . $logline['3'] . ' | ';' . $logline['4'] . ' | ';
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!
December 11th, 2005 at 1:01 am
what if i’d like to know what country is IP from… ?? how could i do that ??