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.

expert residential cleaners Park Ridge ..
In The News:

The Omoway Omo X features a modular design, obstacle detection and emergency braking, and can drive itself to charging stations, signaling the future of smart urban mobility.
PillTrek, a tiny wireless smart capsule created by Caltech, provides real-time gut health data by detecting electrolytes, metabolites, glucose, hormones, pH levels and temperature.
Learn to spot fake bank text messages with five warning signs of Chase phishing scams, including suspicious links and urgent deadlines designed to steal your account information.
Robot coyotes built on motorized cars reaching 20 mph are being deployed at military airfields as an innovative solution to wildlife threats to aircraft safety.
Explore Google Drive's strengths and weaknesses as a backup solution, including its encryption security, privacy concerns and comparison to dedicated backup tools.
As environmental challenges grow, underwater habitats gain momentum with DEEP's Vanguard, supporting short missions and Sentinel designed for 28-day stays at depth.
The new Urban Eyes safety vest features dual cameras, reflective panels and a wireless remote to deter harassers and provide peace of mind for outdoor workouts.
The $200 billion data broker industry tracks your personal details across websites, posing privacy risks that can be mitigated through data removal services.
UCC Holding has teamed up with COBOD to create desert-inspired, 3D-printed schools in Qatar, featuring dune-like wavy walls impossible with conventional construction.
Darkling beetles equipped with microchip backpacks can be guided through disaster areas using electrical signals, offering a biological solution for search and rescue.
Scammers use number porting to take control of outdated landlines still connected to financial accounts, bypassing two-factor authentication to steal funds while avoiding detection.
Twitter co-founder Jack Dorsey developed Bitchat, a privacy-focused messaging app that works offline via Bluetooth without requiring email, phone numbers or personal data.
Google is making a push to ensure its AI, Gemini, is tightly integrated with Android systems by granting it access to core apps like WhatsApp, Messages, and Phone.
A new green energy system is set to change how we capture clean power, and it all starts with the ocean. French startup Seaturns has designed technology that taps into the natural motion of the sea.
Cybersecurity researchers are warning that hackers have started exploiting flaws in chatbots to carry out AI phishing attacks.
Google has just made it easier than ever to regain control of your inbox with Gmail's new Manage Subscriptions tool.
Despite the benefits, residential power saver programs come with several potential drawbacks and concerns that have been raised by both customers and experts.
The Blackdot AI tattoo machine is quiet. It's steady. And according to early users, it hurts a lot less.
Attackers have started to exploit the very signals that users assume will keep them safe when it comes to add-ons to improve productivity or entertainment.
Located on Cerro Pachón in Chile, the world's most powerful digital camera is set to transform how we see the universe.
The innovative DQ Tower stands 28 feet tall with 420 square feet of living space, featuring floor-to-ceiling windows and premium amenities in a prefabricated design.
A new mmWave imaging system allows warehouse robots to scan and create 3D models of objects inside sealed containers, potentially revolutionizing shipping processes.
Family fraud endangers seniors when relatives exploit their trust, but removing personal data online and monitoring identity can prevent financial harm to aging parents.
A study analyzing 500,000 customer service interactions shows chatbots struggle with complex issues while human agents excel at matching customer communication styles.
Aigen's Element robot uses solar power and AI to provide farmers with a sustainable alternative to herbicides, working efficiently in cotton and soy fields.

Maintaining Your Business Website

QUESTION: Should I build and maintain my business Web... Read More

Web Designer? You Dont Need No Stinkin Web Designer!

RIVERSIDE, CA August 4, 2004 ?- "Historically, small business owners... Read More

Database Driven Web Site - Do You Need It?

Many of site owners still don't realize all advantages of... Read More

Maximizing ROI via Web Site Traffic Analysis

We are clearly well past the innocent "golden age" of... Read More

Improving Usability for Screen Reader Users

Simply ensuring your website is accessible to screen reader users... Read More

Build It and They Will Come

Build it and they will come is not always true;... Read More

7 Tips to Make Your Order Page Work Harder

So your prospect, Mary, is sitting at the computer reading... Read More

Freelance Programming is Easy to Manage

There are several reverse bid freelance sites out there. Beyond... Read More

Duplication vs. Individualism

How can we add Word Rich Content to our Websites... Read More

Getting a Web Site Can Be Fast, Easy, and Inexpensive When You Know Your Options

So what do you do if need to get a... Read More

Server Stats ? Analyzing Traffic To Your Site

Analyzing traffic to a site is a key factor in... Read More

Web Coach Tip: What You Should Know About DIY Web Sites

Recently, a friend asked "What's the deal with those DIY... Read More

Getting One-way Inbound Links: the 5 Major Strategies

With search engines putting a damper on direct reciprocal links,... Read More

Ever Wondered What Challenges Other People With Their Web Site?

Have you ever wondered what challenges are faced by other... Read More

UK Online Shopping with an Edge, for Buyers and Sellers Alike

Any new website competing on the internet, needs to take... Read More

Five Steps to Create Your Software Product with Outsourcing

Many executives and investors are skeptical that software products can... Read More

PHP & Account Activation

When a user signs up at your website, you may... Read More

The Number 1 Reason Most Websites Fail

Failure, just like success, is measured differently by each and... Read More

Web Analytics - Getting it Right

Understanding and using web analytics.In recent years, website marketers were... Read More

Why Do I Need A Web Site?

Even though the Internet has been around for a long... Read More

A Beginners Guide to Server Side Includes

An Introduction to Server Side IncludesBeginner? That's OK!While much has... Read More

Build a Web Site that Works...Even for a Safari Hobby!

My life's greatest passion is a safari hobby. And what... Read More

Successful Web Development: 10 Key Elements

There are many elements that are key to successful web... Read More

Five Reasons You Have to Stop Your Web Site

That's right. Your method, behavior and strategy you are now... Read More

2 Key Ways to Make Your Site a Success

If one more business owner tells me their website sucks... Read More

green cleaning service Park Ridge ..