Tuesday 2 June 2015

php hit counter

<?php
// start at the top of the page since we start a session
session_name('mysite_hit_counter');
session_start();
//
$fn = 'hits_counter.txt';
$hits = 0;
// read current hits
if (($hits = file_get_contents($fn)) === false)
{
 $hits = 0;
}
// write one more hit
if (!isset($_SESSION['page_visited_already']))
{
 if (($fp = @fopen($fn, 'w')) !== false)
 {
  if (flock($fp, LOCK_EX))
  {
   $hits++;
   fwrite($fp, $hits, strlen($hits));
   flock($fp, LOCK_UN);
   $_SESSION['page_visited_already'] = 1;
  }
  fclose($fp);
 }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Hit Counter Example Code</title>
</head>
<body>
<p>Page content...</p>
<div class="counter">
 <p>This page has <span><?=$hits;?></span> hits</p>
</div>
</body>
</html>
 
 

Usage

What would a PHP code site be without a hit counter? 
So I am throwing in my version of this script. 

Using file_get_contents() for fast reading of the hits, 
implements a session as not to record a hit for the same user again 
and file locking for safe and multiple writes. 

Of course use as is since flock() can block the script execution if 
you have many visitors! For non Windows users you can use a non-blocking 
flock():

if (flock($fp, LOCK_EX | LOCK_NB))

and run a timed loop to wait for some milliseconds before aborting the locking. 
Obviously that would be an overkill of a tiny hit counter.
 

0 comments:

Post a Comment