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.

affordable house cleaning Wilmette ...
In The News:

A massive DHS data leak exposed records of over 41,000 employees, revealing links to undercover ICE operations, Palantir tools and AI platforms.
The Fox News AI Newsletter covers the latest artificial intelligence technology advancements, including the challenges and opportunities AI presents now and for the future.
UCLA's PhoneBot turns old Android phones into the brain of a two-legged humanoid robot that walks, follows people and stands up after falling.
A fake Amazon invoice charging $988.18 for an iPad lists the same customer support phone number three times to steer panicked victims into calling.
A handful of food delivery robots from Uber Eats and other platforms have gotten kicked and knocked over in Philadelphia and Los Angeles.
Data broker opt-out forms may not protect your family. People search sites can still expose your info through a spouse's or parent's profile.
Apple's first touchscreen MacBook Pro starts at $2,899 with a PROLED XDR OLED display, but the non-touch M6 model costs $900 less at $1,999.
Black Friday deals are already drawing scammers who use fake delivery notices and gift card payment requests to steal your personal financial information.
Apple's iPhone Duo reportedly outlasted the Samsung Galaxy Z Fold 8 by over three hours in battery tests, but its weight and repair costs raise concerns.
Florida Polytechnic University's Jetson ONE eVTOL police vehicle named Astro still awaits FAA authorization before officers can fly operational patrols.
OpenAI's new locked chats feature lets you protect ChatGPT conversations with a PIN, Face ID or Touch ID, but there are key privacy limitations.
A phishing email disguised as an Evite fooled a man even after he emailed his friend to verify it, revealing how compromised Gmail accounts aid scams.
Microsoft's AI diagnostic system identified 83% of complex medical cases in a study, more than doubling the 36% accuracy of generalist doctors.
Account takeover threats go beyond stolen passwords as criminals exploit session cookies, SIM swaps and MFA fatigue to bypass your login security.
SpaceX is reportedly pursuing access to 80,000 cell sites to turn Starlink into a major wireless carrier rivaling Verizon, AT&T and T-Mobile.
Tech advocacy groups warn that foreign nationals at AI companies like OpenAI and Google pose a national security threat amid a lack of federal oversight.
Singapore researchers built the world's first touchscreen woven into clothing, surviving 50 machine washes while displaying images and responding to touch.
The Fox News AI Newsletter covers the latest artificial intelligence technology advancements, including the challenges and opportunities AI presents now and for the future.
A startup founder woke to $449 in unexpected OpenAI and Anthropic charges after stolen API keys were exploited during the "Black October" cyber wave.
Educational Testing Service hackers stole millions of California student records, but families who moved out of state years ago may also be affected.
Apple's iPhone Duo screens are cracking near the hinge just days after its $1,999 launch, and iFixit's CT scans may reveal what's going wrong.
Travel expert Katy Nastro says 50,000 American Airlines AAdvantage miles vanished from her account after someone redeemed them without permission.
Google AI Overviews can't be permanently turned off, but adding -AI to your searches and using the built-in Web filter can help bypass AI summaries.
Attaxion researchers found 30 fake Texas campaign merchandise stores traced to just two sellers hawking gear for competing Republicans and Democrats.
GM plans to debut eyes-off driving in the Cadillac Escalade IQ by 2028, but safety testing reveals how long distracted drivers take to regain control.

Beautiful Web Sites Seldom Make More Sales

Designing an E-commerce Web site is not as simple as... Read More

Ecommerce for Beginners

Like most average persons, I wanted some extra money to... Read More

FREE Amber Alert Tickers for Your Website

Project Safekids provides webmasters a valuable tool which could save... Read More

Is Your Web Site Talking to Your Customer?

A while ago one of my clients approached me and... Read More

How To Keep Your Website Sticky

Developing a website with content that entices visitors to return... Read More

Freelance Programming is Easy to Manage

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

The Problem with Paypal On Your Web Page

When I set up my website I felt paypal was... Read More

Setting Up Your First Website

Q. Hey, Cathy: I'm just setting up a website. What... Read More

Marketing Your Business Online

As a business you can't afford to ignore the Internet... Read More

Website Success is Key

The popular search engine Google indexes over 8 billion websites.... Read More

Website Conversion Rate: More Keywords Equals More Sales

Your website conversion rate should concern you. This simply refers... Read More

Credibility - 10 Ways to Build it on Your Website

If you have your own business website and you are... Read More

4 Marketing Tips for Resourceful Webmasters!

The internet is a sea of knowledge. Getting your information... Read More

Topics to Add When Creating an Alternate and Modern Medicine Web Directory

Alternate medicine finds its own place in the hearts and... Read More

Website Survival Guide

In the big, wide online world there are millions of... Read More

How Did You Get Here?

When marketing your website, it's important to know which of... Read More

Ten Major Tips to Develop a Multilingual Web Site to Work

If you are living in a country that its native... 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

7 Questions to Understand Your Customer Better

Customer service questionnaires can help your clients better understand their... Read More

Guide to Internet Business - Website Setup

After planning the design and content of your website, it's... Read More

Improving Usability for Screen Reader Users

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

Database Driven Web Site - Do You Need It?

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

Things to Consider Before Starting a Website

In the time that I have been using the Internet,... Read More

Cost Effective and Powerful Dynamic Websites w. Fantastico Web Hosting

If you are developing your website on a host that... Read More

A Website Is Not Enough

Your ObjectiveYour small business needs an appealing and professional website... Read More

pet-friendly home cleaners Glenview ...