Search

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:

// 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() (http://nl.php.net/mktime) and getHostByAddr() (http://nl.php.net/manual/en/function.gethostbyaddr.php) 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 (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 . "\n";

Shubham Ganeshwadi

Shubham Ganeshwadi

Hi, I’m Shubham Ganeshwadi, Your Blogging Journey Guide 🖋️. Writing, one blog post at a time, to inspire, inform, and ignite your curiosity. Join me as we explore the world through words and embark on a limitless adventure of knowledge and creativity. Let’s bring your thoughts to life on these digital pages. 🌟 #BloggingAdventures

Leave a comment

Your email address will not be published. Email is optional. Required fields are marked *

Your experience on this site will be improved by allowing cookies Cookie Policy