website hit counter php
The following example will demonstrate how you can set up a basic website hit counter in php.
When one user opens a website, his/her session variable is created and default timeout for session is one minute, the counter file is opened and after reading from file one in incremented from existed counter, and if user session is set (user previously browsing website) then simple counter is displayed and to check duration of the session if condition is used and if session duration is maximum than one minute, session is destroyed, next new one is created.
Example
<?php session_start(); // starting user session if(isset($_SESSION['started'])) // check if session is created or not { // opening counter file $fh = fopen("counter.txt", 'r') or die("File does not exist or you lack permission to open it"); // reading counter file $line = fgets($fh); echo "total hits " . $line; fclose($fh); // closing file // checking session, so that it can be expired in 1 minute ( 60 * 1) // represents one minute if((mktime() - $_SESSION['started'] - 60*1) > 0) { unset($_SESSION['started']); } } else { $_SESSION['started'] = mktime(); // assigning time to session variable // opening counter file for reading $fh = fopen("counter.txt", 'r') or die("File does not exist or you lack permission to open it"); $line = fgets($fh); fclose($fh); echo "Total hits " . $line; // opening counter file for writing $fh = fopen("counter.txt", 'w') or die("Failed to create file"); $text = $line+1; fwrite($fh, $text) or die("Could not write to file"); fclose($fh); } ?>