|
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/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 . " ";
// 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.php.net/include):
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://www.php.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.phpit.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 '
echo '
echo '
echo '
echo '
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.php). 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.phpit.net, http://www.aspit.net and http://www.ezfaqs.com.
Eight Deadly Web Site Mistakes and How to Avoid Them
Creating and maintaining an effective presence on the Web has become increasingly complex and challenging as the power of the Internet as a marketing tool becomes more and more necessary to entrepreneurs and emerging businesses.
Five Steps to Create Your Software Product with Outsourcing
Many executives and investors are skeptical that software products can be developed using outsourcing. Even more skepticism is expressed at the idea of outsourcing version 1.0 of a product. Yet Accelerance clients are using outsourcing to create their products right now. What is the secret to using outsourcing to successfully develop a software product?
Successful Web Development: 10 Key Elements
There are many elements that are key to successful web development. There is no arguing that elements of talent such as graphic design, writing, and technical expertise are important. In the long run, however, it is the elements that are not directly associated with web development that determine a website's success. For the beginner, it is important to have a broader view of success
Things to Consider Before Starting a Website
In the time that I have been using the Internet, (since 1996) I have seen a lot of websites. I have seen a lot of good websites and I have seen a lot that were just plain awful. Here are some things to think about before you start a website.
The Secret Benefit Of Accessibility: Part 1 - Increased Usability
Web accessibility has so many benefits that I really do wonder why such a large number of websites have such diabolically bad accessibility. One of the main benefits is increased usability, which according to usability guru, Jakob Nielson, can increase the sales/conversion rate of a website by 100% and traffic by 150%.
5 Essential Traits Of A Home Business Website
So you've decided to start an online work at home business and are just beginning to build your website. You probably have a million different ideas for what you want the site to look like. You will want to take into consideration that your idea of a great website may differ drastically from what a website designed to make sales should be like.
Tell me what your website does!
You know exactly what your organisation does and what your website offers its users. This information has probably become second nature to you, but first-time visitors to your site won't know this. As such, make sure you don't forget to tell them what you do.
New Years Resolutions: Is Improving Your Website One of Them?
With the New Year upon us yet again, it's time to prepare for the successes of 2005. Did you watch with envy last year as your competitors dominated your industry? Do you think your site is doing just fine because no one has ever called to complain? Well here's some food for thought: 96% of all prospects will click over to your competitor if they encounter a problem on your website.
Autoresponders Make You Look Like A Pro
People like to get immediate responses to requests. Autoresponders are great for letting people know you are on the job and that their requests are being taken care of. These are much better than thank you pages.
Duplication vs. Individualism
How can we add Word Rich Content to our Websites without overtly duplicating others website content, and as an end product maintain our own Individualism?
Improve Conversion Rates ? Effective Content
Your site is fast and getting traffic, but conversion rates are disappointing. You may have problems with the tone of your content
You May Be Losing Valuable Traffic - And Not Even Know It!
Here's something you may never have thought of before:
Ten Quick Tests To Check Your Website For Accessibility
The Disability Discrimination Act says that websites must be made accessible to disabled people. So how can you check that your website is up to par? There are a number of basic tests you can make to address some of the main issues that provide a good start in increasing accessibility to your site visitors:
Website For The Company Store
If your company own one or more stores, you might be wondering if it would be a good idea to have a website. You might also be wondering if a website for the company store would be profitable for your business.
Setting Up Your First Website
Q. Hey, Cathy: I'm just setting up a website. What should I do?
Learn What 98% of Targeted Visitors Do On Your Website
Getting a Targeted Visitor to a website is a waste of time and money if you've got no idea what 98% of them do when they get there.
3 Rules of Website Designing and Layout
Now that you have got your domain name registered, your next worry is about designing a website or getting it designed, depending on your budget,inclination and knowledge.
10 Tips For A Successful Website
Have you ever thought the secret behind the success of most of the famous sites. Do you ask yourself these questions. Why do they get so many clicks?Why they are making so much money and i am not?Why only few web sites succeed and most of others fail?Just stop questioning and start reading.
Are Web Graphics Stealing Your Money?
They might not be wearing a mask and carrying a gun, but if you've got images on your web pages then they could be costing you a lot more money than you think every time a visitor looks at one. That's because image files are typically the biggest bandwidth user on any web page. Whenever a visitor's browser is displaying an image on your site, it's actually downloading that image to the local user's hard drive. When anything gets downloaded, it uses bandwidth and bandwidth costs money. The moral of that story is: The bigger the image the more bandwidth it consumes.
You Need a Website!
No matter the size of your business, having a web site is a low cost way to market your services and products twenty-four hours a day. Web sites are a constant advertisement for your business and will help you reach your targeted customers effectively. Your business will not be able to compete without a well-designed web site. There are several key elements to consider when you make the decision to start a new web site: