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.php.net/mktime) and getHostByAddr() (http://nl2.php.net/mktime) 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://nl2.php.net/mktime.

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://nl2.php.net/mktime) and fwrite (http://nl2.php.net/mktime).

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://nl2.php.net/mktime):

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:

// 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://nl2.php.net/mktime), 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://nl2.php.net/mktime) 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://nl2.php.net/mktime). 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://nl2.php.net/mktime.

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://nl2.php.net/mktime, http://nl2.php.net/mktime and http://nl2.php.net/mktime.

In The News:

Apple recently notified a small number of iPhone customers in 92 countries that their phones may be under attack by mercenary spyware.
An artificial intelligence-powered home security system can fire paintballs and tear gas at trespassers. The camera identifies human faces and animals.
Technology expert Kim Komando gives her tips and tricks on enhancing your user experience a smartphone and other devices you use everyday.
A new camera called NUCA uses artificial intelligence to create deepfake photos of subjects by stripping away clothing in close to real time.
The Kimberley Kube trail-ready camper has a compact but spacious design and combines luxury, functionality and ruggedness for a weekend getaway.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Emails instructing you to reset your password for an account may be legitimate, or they may be scams. Kurt "CyberGuy" Knutsson explains.
Northrop Grumman's Manta Ray uncrewed underwater vehicle aims to revolutionize undersea missions — it glides through the ocean without human assistance.
Learn how to work Google's calendar application to streamline and organize your daily tasks from technology expert Kim Komando.
If you do not want Facebook to have automatic access to your private photos, follow our tips to protect yourself. Kurt “CyberGuy" Knutsson shows you how.
Kurt “CyberGuy" Knutsson goes into detail about Apple’s recent iOS update that allows iPhone users to instantly translate spoken language simply by using the Action Button.
Safeguarding your digital life with a reliable physical backup isn't just a precaution, it's a necessity. Kurt “CyberGuy" Knutsson provides the essential backup checklist.
Kurt “CyberGuy" Knutsson reveals how a Redditor exposed false recycling claims at their apartment, highlighting a report that only 21% of U.S. recyclables are processed.
Kurt "CyberGuy" Knutsson offers a travel toolkit featuring five technology tools to help you with booking flights and hotels for your summer vacation.
The bubble behind the clock on your iPhone can appear in different colors. Kurt "CyberGuy" Knutsson explains what each of those colors mean.
Scammers are using the power of artificial intelligence to mimic voices of people and are using the fake voices to commit crimes, like kidnappings.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Tech guru Kurt "CyberGuy" Knutsson explains the science behind the Invisibility Shield, a 6-foot shield that makes people become invisible.
The International Olympic Committee on Friday announced plans to use AI in various Olympic aspects, including athlete identification, training and judging.
Tech guru Kurt "CyberGuy" Knutsson explains an easy trick to avoid squinting while working or surfing the web by zooming in on your personal computer.
Streaming giant Roku has recently been targeted by a pair of cyberattacks, and the company confirmed over a half million Roku accounts were compromised.
The Land Aircraft Carrier combines an all-terrain, six-wheeled vehicle with a two-seat aircraft, which features electric vertical takeoff and landing.
The European Union has sent TikTok a "request for information" on the video sharing platform's newest app, TikTok Lite, under the Digital Services Act, with the aim to clean up social media.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
The FBI is warning the public about a recent phishing scam via text that claims its targets owe money in Pennsylvania for unpaid road toll charges.

Flash Deadly Sins (That Can Kill Your Web Business)

Looks like every client wants a Flash site these days... Read More

Learn to Build a Better Online Business Website Using Keywords and Content

Are you aware that 90% of the websites on the... Read More

Dreamweaver 8 Preview

August 8 2005, Macromedia announced a release of Studio 8.... Read More

Beware the Software Siren

I've heard several prominent web marketers mention in their classes... Read More

1 Simple Solution to All Internet Marketers about Their Website Design Needs

It is an undeniable fact that not everybody is keen... Read More

Web Measurement: What You Don?t Know Would Make A Great Book

"What's in it for me?" you ask. "Why should I... Read More

You May Be Losing Valuable Traffic - And Not Even Know It!

Here's something you may never have thought of before:If I... Read More

5 Sure Fire Ways To Send Visitors Away For Good

So your traffic is going through the roof yeah? It's... Read More

Using Psychology Easily on Your Website to Make More Sales!

Psychology is a long word which everyone thinks, "no, that's... Read More

Newsletter Management Using PHP w/o mySQL for Beginners

Let's begin by setting some limits. If you're like me,... Read More

Allocating Your Web Site?s Budget Properly

I had a client say something to me the other... Read More

Developing State-enabled Applications With PHP

Installment 1Developing State-enabled Applications With PHPWhen a user is browsing... Read More

4 Rock Solid Reasons For Building Your Own Website

What is the point of having a website, you may... Read More

10 Things You Should Be Monitoring On Your Website

Every business needs to know how it is doing. That's... Read More

MySQL Database Handling in PHP

Most interactive websites nowadays require data to be presented dynamically... Read More

Are You Being Scammed By Your Web Design Company?

This is a growing concern amongst many business owners. Does... Read More

Web Content Strategy 101

Your content is what gets you in search engines, speaks... Read More

Remember This When Building A New Site - Beginners Guide

I recently helped my mom to launch a website (www.mom2me.com)... Read More

How Your Own Website Helps Your Small Business Grow

What do you mean, you don't have a website for... Read More

How to Promote Your Law Firm Website On the Internet for Maximum Profit

Making maximum profit from your law firm website is important,... Read More

Instant Relevant Web Site Content - No Its Not a Bot

In about the Time it takes to Watch a Reality... Read More

Is Your Website Doomed for Failure Before Youve Built It?

One of the things that many people overlook when building... Read More

Earning From Your Website

Before you start building your site, ask yourself "WHY?". Why... Read More

Content Management

More and more businesses are recognizing the importance of content... Read More

Better Web Site ROI: Efficient Online Business with SEO, PPC, Split Testing, and Forums

If you're looking for better web site ROI, chances are,... Read More