ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Track your visitors, using PHP

(Page 2 out of 4)

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 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 . "\n";

// 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:

include ('log.php');

« Previous: Getting the information
Next: Viewing the log file »



One Response to “Track your visitors, using PHP”

  1. david Says:

    what if i’d like to know what country is IP from… ?? how could i do that ??

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Getting the information
  2. Logging the information
  3. Viewing the log file
  4. In Conclusion...
Bookmark Article
Download Article
PDF
Download this article as a PDF file