Hi,
I have a HTML Page and i want to get the Hit count of this page once opened and to be displayed in that HTML page using a text file which will store the value of count.
Thanks in advance....
Ravi
Hi,
I have a HTML Page and i want to get the Hit count of this page once opened and to be displayed in that HTML page using a text file which will store the value of count.
Thanks in advance....
Ravi
The approach suggested by and the examples from work as a starting point, but they omit a few practical details that will cause problems under real use: race conditions when two visitors load the page at the same time, file permissions, and how to show the count on a static HTML page. A robust, simple solution is to let a small server-side script do the increment with atomic writes and integer casting.
A minimal, safe PHP endpoint example:
<?php
$path = __DIR__ . '/hits.txt';
if (!is_file($path)) {
file_put_contents($path, '0', LOCK_EX);
}
$hits = (int) @file_get_contents($path);
$hits++;
file_put_contents($path, (string)$hits, LOCK_EX);
echo $hits;
?> This uses atomic file writes (LOCK_EX) and forces numeric casting to avoid corruption. For concurrency control you can also use flock() for more complex flows; see the PHP docs for details (file_put_contents, flock).
If the page must stay as .html, do not rename it: call the PHP endpoint via JavaScript and inject the returned number into the page. A tiny client-side example would fetch the value and put it into an element with id hits. See MDN for the Fetch API (Using Fetch).
Troubleshooting and cautions:
These additions make the basic text-file counter reliable and safer in production compared with the raw snippets posted earlier.
Jump to Post— Shanti C 106<?php $data2 = file_get_contents("data2.txt") + "1"; $fp = fopen("data2.txt", "w"); fwrite($fp, $data2); fclose($fp); ?>
<?php
$data2 = file_get_contents("data2.txt") + "1";
$fp = fopen("data2.txt", "w");
fwrite($fp, $data2);
fclose($fp);
?> or use this:
<?php
$text_file = "hits.txt";
function hitCount($file) {
$fp = fopen($file,rw);
$count = fgets($fp,9999);
fclose($fp);
$fp = fopen($file,w);
$count += 1;
print "$count ";
fputs($fp, $count);
fclose($fp);
}
/* display it on your page */
echo 'Page hits:' . hitCount($text_file);
?> We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.