Business Articles, Internet Resources and Tutorials - Senyum

Titles Titles & descriptions

Google Catalogs - Old Gashioned Mail Order Meets High Tech Search
In addition to Google's Froogle shopping service (still in beta), which features a searchable database of onli...

Organization and the Opposite Sex
In many of the companies I have worked in, there is a very high proportion of male managers to females. This c...

Depression Keeps 19 Million Adults From Being Productive
Approximately 19 million American adult workers allow depression to limit their productivity. According to th...

Articles Tutorial
Articles on advertising, sales management, business, stock market, hobbies, health, lifestyle, family relationships, online business, money, stock trading and m...


Link Exchange

Exchange links with our website.


Sponsored Links

   

Track Your Visitors, Using PHP

Navigation: Main page » Web Development

 Print this page 

Author: Dennis Pallett

Article source: http://www.articlecity.com/. Used with author's permission.

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 '

';

echo '

';

echo '

';

echo '

';

echo '

';

foreach ($log as $logline) {

echo '

';

echo '

';

echo '

';

echo '

';

echo '

';

echo '

';

echo '

';

}

echo '

IP Address Referrer Date Useragent Remote Host
' . $logline['0'] . ' ' . urldecode($logline['1']) . ' ' . date('d/m/Y', $logline['2']) . ' ' . $logline['3'] . ' ' . $logline['4'] . '
';

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.




The Best Way To Give Medicine To A Baby
You have a spoon full of medicine for baby in one hand, and you're holding baby in the other. So how do you get the spoon in her mouth?!

Small Business Planning -- Three Myths
Planning isn't just for people seeking money. It's vital to the success of your small business.

Help! Your Heart is Missing From Your Scrapbooking Journaling - Part 5
Want to take a different approach to scrapbooking journaling? Find out how scrapbooking journaling from your heart can help you journal better. This is part fiv...

10 Questions About Cellular Phones Answered
Facts you should know when buying a new cellular phone or choosing a cell phone plan.

Coaching Prime Time
An awful lot of fantastic coaching has been coming out of Hollywood lately, have you noticed?

Raising Issues In Your Group or Offline
Drawing on his experience with clients as they've tried to deal with emotionally-sensitive topics in their groups, Matt offers three principles to help you deci...

Benefits of Soy in Facial Creams
Soy helps with Skin Regeneration and Deep Moisturising!

An Overview of the Gatlinburg Cabins
Originally founded in the early 1800s as White Oaks, Gatlinburg was just a sleepy residential town until the growth of its lumber industry in the early 1900s. T...

Use Real-Life Templates For Writing Success
At some point along the way, most of us have used what are commonly called "fill-in-the-blank" writing templates. We might have used them to write a letter, for...

Gift Baskets - Create Simple Easy Gifts For the Person Who Has Everything!
Have you ever wanted to create personalized gift baskets? For the person who has everything gift baskets are very simple and easy to create! You are only limit...

4 Simple Tests To Find Good Real Estate Investment Properties
Finding best deals of investment properties doesn't have to be a guessing game. Learn the 4 simple tests to find the good value investment properties here!

Why Commercial Real Estate is the Hottest Retirement Asset
For Successful Small Business Owners, Commercial Real Estate Investment is the Hottest New Retirement Asset

Wholesale Body Jewelry: How To Find The Best Wholesale Body Jewelry Deals For EBay
Wholesale body jewelry is a hot product category for eBay sellers.

Why Clean Mobile Homes for a Business?
Manufactured and Mobile Home owners know that the weather this year will be quite harsh. It's imperative these owners to clean out rain gutters and debris from...

Weight Loss with Hoodia Gordonii
Hoodia gordonii is believed to contain the natural appetite suppressant property. Some studies have reported its hunger suppressant effect.

A Guide to Home Dehumidifiers
It can be difficult to choose from among the countless home dehumidifiers out there. First, determine the square footage of the largest room you plan to dehumid...

The Hated Cellulite Cure That Works
How do women in the advertisements for cellulite creams get rid of their cellulite? Not by using a cream, of course. One may answer that Adobe Photoshop editing...

Golf Stretching Secrets to Improve Performance
The trend in larger and therefore heavier club heads in recent years has made golf stretching secrets even more important to acquire.

10 Ways To Gain An Avalanche Of Sales
1. Utilize holidays to increase your visitors or sales. You could give away free electronic greeting cards, hold discounts, send customers holiday cards, etc. 2...

Is Starting A Business For Me? What To Consider Before Starting A Business
Do you have the right temperament? Starting a small business is one of the most serious decisions that a person can take in life. Positively, it often results i...

Internet Marketing - Article Announcer
Reflection on being a newbie in this business to the today in the life of an internet marketer. An introduction to ArticleAnnouncer.

How to Create an Interest Story for the Press
If you think you have something that is interesting and you could bring attention to your company because of it, then you need to read through this article. Thi...

A Day in Your Life: 17 Ways to Make it a Special Day
Life brings a muliplicity of emotions, events, defeats, and victories. Each day is a brief and precious time to experience its vast range of emotions and react ...

White Sun - The Spiritual Test
A piece of twisted and decayed wood cannot be used for carving. A wall made of loose mud cannot be painted. Test is only given to those who are qualified. Jesus...

 
Newsletter


Article Categories

Home
Web & Online Business
Affiliate Revenue
Auctions
Blogging RSS
E-Books
E-Commerce
Email Marketing
Ezine Publishing
Internet Marketing
PPC Advertising
SEO
Security
Site Promotion
Spam Blocker
Traffic Building
Web Design
Web Development
Money & Finance
Credit
Currency Trading
Debt Consolidation
Debt Relief
Insurance
Investing
Loans
Mortgage Refinance
Personal Finance
Real Estate
Stocks Mutual Funds
Taxes
Wealth Building
Business
Advertising
Branding
Business Tips
Careers Employment
Copywriting
Customer Service
Entrepreneurialism
Management
Marketing
Networking
Network Marketing
Presentation
Public Relations
Resumes & Cover Letters
Sales
Sales Management
Sales Training
Small Business
Strategic Planning
Team Building
Health & Medicine
Acne
Alternative Medicine
Beauty
Depression
Diabetes
Exercise
Fitness Equipment
Hair Loss
Medicine
Meditation
Men's Issues
Muscle Building
Nutrition
Nutrition Supplements
Weight Loss
Women's Issues
Yoga
Family & Relationships
Babies Toddler
Dating
Holidays
Home Improvement
Interior Decorating
Landscaping & Gardening
Marriage & Wedding
Parenting
Pregnancy
Relationships
Sexuality
Hobbies & Lifestyle
Casinos & Gambling
Cooking Tips
Crafts & Hobbies
Fashion & Style
Golf
Humanities
Mobile Cell Phone
Music
Outdoors
Pets
Photography
Poetry
Politics
Recipes
Science
Vacation Rentals
Writing
Writing Articles
Self-Improvement
Attraction
Coaching
Creativity
Goal Setting
Grief & Loss
Happiness
Innovation
Inspirational
Leadership
Motivation
Organizing
Positive Attitude
Religion
Spirituality
Stress Management
Success
Time Management


www.senyum.net - This website contains articles on wide range of topics. Articles on advertising, sales management, business, stock market, hobbies, health, lifestyle,
family relationships, online business, money, stock trading and many more are available.
www.senyum.net covers USA, UK, Canada, Australia, China and Germany : - complete articles online business - articles tutorial.
Copyright © 2006 SmileMedia Co. All rights reserved.