How to Add a Counter to a Page With PHP
- 1). Create a text file to store the accumulated visit count for your web page. Use your text editing software to create a new empty file, and save it. This file should be stored in the same folder that contains your page's HTML files. For the example that develops over the following steps, the file is named "visit_count.txt", but you may name the file anything you please.
- 2). Create a PHP file with your text editor. This file contains the script and is called from your web page whenever the counter is to be displayed. Name this file something applicable, such as "hitcounter.php."
- 3). Open the accumulator file within the PHP script, and read the number contained within. This process requires that you open the file, read the text number and assign it to a variable. The variable ($hitcount in this example) is incremented by one and then rewritten to the file. The file is then closed, and the visit count is returned to the web page. Add the following code to the "hitcounter.php" script:
<?php
$file = fopen("visit_count.txt",(is_file("visit_count.txt"))?"r+":"w+");
$hitcount = trim(fgets($file)) + 1;
fputs($file, $hitcount);
fclose($file);
echo $hitcount;
?> - 4). Call the PHP script from within your web page wherever you want to display the visitor count. For example, the following HTML statement calls the PHP script as a part of displaying some text:
<p>Page has had <b><?php include("hitcounter.php"); ?></b> visits.</p>
Source...