A Basic PHP Statistics Script

In this tutorial you will learn about writing information to a text file and then retrieving the information you wrote to the text file. Retrieving the files that are in a directory and about arrays.

This is a quite basic script and there isn't much to write about it so if there is something that you don't understand look the function up within the PHP manual online.

Step 1

In the first step we are going to get the current page that we are at and store it within a variable. The information in that variable will then be wrote to a file called stats.txt.

Include the following code in the pages that you want the number of visits to be counted for. If you have a file such as a header file than put this code in there.

<?php
 
// write current page to stats file
$cur_page = $_SERVER['REQUEST_URI'];
if(empty($cur_page)) {
	$cur_page = 'index.php';
}
$file = fopen("stats.txt", "a+");
fwrite($file, $cur_page . "\n");
fclose($file);
 
?>

Step 2

The next piece of code that we are going to write is going to retrieve the information in stats.txt and put it into an array. We then use the function array_count_values to see how many times the page url occurs. We also retrieve the files in the directory which this script is in to compare them with the files in stats.txt.

<?php
 
$file = fopen("stats.txt", "r");
$files = scandir('./');
$num_files = array();
while(!feof($file)){
	$line = fgets($file);
	$line = substr($line, 1, -1);
	$line = explode(",", $line);
	array_push($num_files, $line[0]);
}
 
 
$num_cv = array_count_values($num_files);
 
foreach($num_cv as $f => $c) {
	echo 'file: ' . $f . ' - ' . $c . '<br>';
}
 
?>

If you have any other alternatives or need any help then feel free to post a comment.

Bookmark and Share
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • Ping.fm
  • Tumblr
  • Twitter

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

, , , , , , , , , , , , , ,

3 Responses to A Basic PHP Statistics Script

  1. Design Jar March 31, 2009 at 1:54 pm #

    Great vid, helps me so much more when you can see explanations rather than reading.

  2. Xavier_3D June 5, 2009 at 7:10 am #

    Hey Wez. Care to spare sometime. I may need your assistance in an area.

    Please contact me. I have updated my profile here.

  3. ManiG August 5, 2009 at 5:37 am #

    Your tutorials were amazing

Leave a Reply