Stats have become really important over the past few years, businesses are investing thousands of dollars into knowing who visits their sites, and for good reason.
I'm going to show you a simple way of recording data about your visitors.
Firstly, open up NotePad and create a blank document, save it as
visits.txt.
Upload the file and then chmod it to
777 - this means we can write to the file...
Now for the code that records visitor data...
Lets begin by opening the file and setting the variables:
Code:
<?php
$dtime = date('F jS Y, h:iA');
$ip = $_SERVER['REMOTE_ADDR'];
$host = gethostbyaddr($ip);
$agent = $_SERVER['HTTP_USER_AGENT'];
$uri = $_SERVER['REQUEST_URI'];
$ref = $_SERVER['HTTP_REFERER']; Explination Of Variables: $agent - The visitor's Web Browser
$uri - The URL they are viewing
$ip - The visitor's IP Address
$ref - The reffering URL
$host - The visitor's Host
$dtime - Date and Time of visit
---
Now, a little bit of error handling...
If a field is left blank, we're going to replace it with "None Recorded".
Code:
if($dtime == ""){
$dtime = "None Recorded";
}
if($ip == ""){
$ip = "None Recorded";
}
if($host == ""){
$host = "None Recorded";
}
if($agent == ""){
$agent = "None Recorded";
}
if($uri == ""){
$uri = "None Recorded";
}
if($ref == ""){
$ref = "None Recorded";
} ---
Now we're going to set what is to be written in our text file.
Code:
$entry_line = "
Date: $dtime
IP: $ip
Host: $host
Browser: $agent
URL: $uri
Referrer: $ref
---------------
";
This will simply write all the collected infomation and then seperate each entry with ---------------.
---
All we now need to do is open the txt file, write the entry, close the text file and then close the script...sound difficult? It really isn't!
Code:
$fp = fopen("visitors.txt", "a");
fputs($fp, $entry_line);
fclose($fp);
?> fopen opens the specified file.
fputs writes to the file.
fclose closed the file.
?> ends the script.
---
Here's the full script: (All code together)
Code:
<?php
$dtime = date('F jS Y, h:iA');
$ip = $_SERVER['REMOTE_ADDR'];
$host = gethostbyaddr($ip);
$agent = $_SERVER['HTTP_USER_AGENT'];
$uri = $_SERVER['REQUEST_URI'];
$ref = $_SERVER['HTTP_REFERER'];
if($dtime == ""){
$dtime = "None Recorded";
}
if($ip == ""){
$ip = "None Recorded";
}
if($host == ""){
$host = "None Recorded";
}
if($agent == ""){
$agent = "None Recorded";
}
if($uri == ""){
$uri = "None Recorded";
}
if($ref == ""){
$ref = "None Recorded";
}
$entry_line = "
Date: $dtime
IP: $ip
Host: $host
Browser: $agent
URL: $uri
Referrer: $ref
---------------
";
$fp = fopen("visitors.txt", "a");
fputs($fp, $entry_line);
fclose($fp);
?> Save it as
visitors.php and use php include on each page to record visitor data from that page.
PHP Include: Code:
<?php include("visitors.php"); ?> ---
Use this data wisely. I reccomend that you have a "Privacy Policy" describing the fact that you are collecting this data and that you wont be sharing it with any third partys ;)