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.
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.
If you have any other alternatives or need any help then feel free to post a comment.
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>'; } ?>
No comments:
Post a Comment