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://nl2.html.net/mktime) and getHostByAddr() (http://nl2.html.net/manual/en/function.gethostbyaddr.html) 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.htmlit.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.html.net/fopen) and fwrite (http://www.html.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.html.net/include):

include ('log.html');

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:

// Open log file

$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 (http://www.html.net/explode), like so:

// Seperate each logline

$log = explode(" ", 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:

// 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() (http://www.htmlit.net/count) on the $log array, and there you have it;

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:

// Show a table of the logfile

echo '';

echo 'IP Address';

echo 'Referrer';

echo 'Date';

echo 'Useragent';

echo 'Remote Host';

foreach ($log as $logline) {

echo '';

echo '' . $logline['0'] . '';

echo '' . urldecode($logline['1']) . '';

echo '' . date('d/m/Y', $logline['2']) . '';

echo '' . $logline['3'] . '';

echo '' . $logline['4'] . '';

echo '';

}

echo '';

You can also use custom functions to filter out search engines and crawlers. Or create graphs using PHP/SWF Charts (http://www.maani.us/charts/index.html). 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-ass traffic analyzer.

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

About The Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.htmlit.net, http://www.aspit.net and http://www.ezfaqs.com.


MORE RESOURCES:
RELATED ARTICLES
Benefits Of An Accessible Website: Part 2 - The Business Case
The DDA (Disability Discrimination Act) states that service providers must not discriminate against disabled people. A website is regarded as a service and therefore falls under this law, and as such must be made accessible to everyone.
CPanel Fantastico - Features and Benefits
Fantastico is a 3rd-party cPanel add-on and can be purchased and added to the standard cPanel interface. Fantastico allows you to quickly install a variety of open-source scripts.
Streamline your Business Website with a Content Management System
I talk with so many people who have small businesses and would like to have a web presence but don't know the first thing about how to even get started. Some of the reasons I hear are:- I don't know how to build a website.
Introductory PHP For Non-Programmers
When you started reading this sentence you assumed lo acabaría en inglés. However, I didn't finish in English.
How to Create Sizzling Sales online
"Don't Sell the Steak, Sell the Sizzle."Have you heard of this phrase before? It has been widely regarded as "principle number one of salesmanship" as far back as 1936.
Product Promoting: Getting The Response
When you publish a content site there are times when affiliate products are not the only products you want to recommend.Situations when you'll find you'll want to promote a non-affiliate businesses' product(s).
You May Be Losing Valuable Traffic - And Not Even Know It!
Here's something you may never have thought of before:If I were to type your domain name?http://www.yourdomain.
Art, Artists, and the Web:Part: 2--First Steps in Building an Artist's Website
What you should do and know if you are an artist and you have decided to have a website.1) Look at "Web Sites That Suck.
How Disabled Users Access The Internet
In 1995 a new era of accessibility for disabled people began. The Disability Discrimination Act was passed, stating that:"It is unlawful for a service provider to discriminate against a disabled person by refusing to provide any service which it provides to members of the public.
If Its Done Its Done for: Make Your Website Part of Your Business before You Build
Web sites are an Ongoing Part of Business.All too many small business owners build a web site that is considered complete once the final copy is placed.
A Web Site for Your Small Business: How to Set Up a Website
Your web site will be your window to the world. Even if you are not selling any product online still you need your customers to access you 24 hours a day 365 days in a year and you can pass important information to them by hosting frequently asked pages, product descriptions, product improvements etc.
The 5 Biggest Mistakes Almost All Web Designers Make
Huge Mistake #1: Creating a Website with Flash -- Did you know in a recent study, top internet marketers discovered that having a website created with Flash, actually DECREASED the response from prospects and customers by as much as three-hundred-and-seventy percent?Here's why: Your prospects and customers are most likely visiting your website using all types of different computers, connection speeds and internet configuration settings..
3 Ways To Increase Your Websites Conversion rate
Everywhere you look these days, people are telling you that in order to sell through your website, you need tons of traffic.Well, even though my business is traffic generation, *I'm* going to tell you that it's a BIG FAT LIE!The secret of a successful website isn't just in the amount of visitors it has; it's in the amount of visitors that are converted to buyers.
Running An Effective Website
Running an effective website is a continuous process. I have compiled five (5) ways of doing it on a regular basis.
Web Coach Tip: What You Should Know About DIY Web Sites
Recently, a friend asked "What's the deal with those DIY companies that advertise "How to get a website with everything your business needs for under $20 bucks a month?". "How can they do that?" she said.
Planning Your Website for Success
Most people know they need a website in order to publicise and promote their business but very few people know what they want in their website. Fewer still are those who can actually sit down and plan their websites well.
Establishing Your Web Presence
Part of the success of most home-based businesses is their web presence. After all, you want to benefit from the global exposure, reduced marketing expenses, and low entry costs.
Three Things Every Website Should Do
When I started my company in 2002, I knew I needed to have a website. Why? To provide credibility! How can a company be "real" in this day and age if it doesn't have a website? So, like many companies, I published an informational website that explained "here's who we are, and here's what we do".
Setting Up Your First Website
Q. Hey, Cathy: I'm just setting up a website.
What Business Owners MUST Know BEFORE They Commit To Having A Web Site
Q1.Why would I need a web site? A1.