Thursday, August 6, 2009

PHP Hit Counter using text only

Steps to make a Hit Counter

1. Create a counter text file of the name hitcounter.txt and save it to the same directory you will put your hit counter in.


2. Open your php editor. Save the document as counter.php. Set your opening statement for PHP script.

<?php
?>

3. Set the variable for the file named hitcounter.txt and place this between your PHP tags. remember to place the filename in quotes. place the semicolon on the end of the line to end the command.

<?php
$count_my_page = ("hitcounter.txt");
?>

4. Set the number of visits to the current value of the contents of the hitcounter.txt file:

<?php
$count_my_page = ("hitcounter.txt");
$hits = file($count_my_page);
?>

5. When the script is accessed as the page loads, it not only reads the current number of hits on the page in the hitcounter.txt, it must increase the value by 1 for the current hit to be recorded. Add 1 to your value of $hits and call it $hits.

<?php
$count_my_page = ("hitcounter.txt");
$hits = file($count_my_page);
$hits[0] ++;
?>

6.Open the file that is keeping count so we can write to it

<?php
$count_my_page = ("hitcounter.txt");
$hits = file($count_my_page);
$hits[0] ++;
$fp = fopen($count_my_page , "w");
?>

7. Replace the value in the file with the new $hits number after it was incremented.

<?php
$count_my_page = ("hitcounter.txt");
$hits = file($count_my_page);
$hits[0] ++;
$fp = fopen($count_my_page , "w");
fputs($fp , "$hits[0]");
?>

8. You must close the file next.

<?php
$count_my_page = ("hitcounter.txt");
$hits = file($count_my_page);
$hits[0] ++;
$fp = fopen($count_my_page , "w");
fputs($fp , "$hits[0]");
fclose($fp);
?>

9. Set the code to display your hit number.

<?php
$count_my_page = ("hitcounter.txt");
$hits = file($count_my_page);
$hits[0] ++;
$fp = fopen($count_my_page , "w");
fputs($fp , "$hits[0]");
fclose($fp);
echo $hits[0];
?>

10. Save your php file in same directory as the text file.

11. To use this script you just have to add a php statement that calls that php file. Use the following include:

<?php
include ("counter.php");
?>