Skip to content

Instantly share code, notes, and snippets.

@RahulSaini91
Last active March 5, 2019 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RahulSaini91/a09c8f8e6cebf4c66e227699f5860df3 to your computer and use it in GitHub Desktop.
Save RahulSaini91/a09c8f8e6cebf4c66e227699f5860df3 to your computer and use it in GitHub Desktop.
<?php
/*-----------------------------------------------------------
| @Visitor Counter without using database
| github: https://gist.github.com/RahulSaini91/a09c8f8e6cebf4c66e227699f5860df3
| Save visiter number in cookies
|
| Access the visitor count
| echo the_counter();
|
| Get it into a variable
| $visitor_num = the_counter()
*/
session_start(); error_reporting(0);
$file_name = 'count'; // set the file location and name to save counting numbers
$use_cookie = 1;
//print the visitor counter number
echo the_counter();
/*------------------------------------------------------
| @read file if exists and return the content of file
-------------------------------------------------------*/
function read_file($file){
if(file_exists($file)){
$f = fopen($file,'r');
$f = fread($f,filesize($file));
fclose($f);
return $f;
}
}
/*-------------------------------------------------------------
| @write the file by using overwrite method if file exists
--------------------------------------------------------------*/
function write_file($file,$data){
$f = fopen($file,'w');
$s = fwrite($f,$data);
fclose($f);
return $s;
}
/*-------------------------------------------------------------
| @return the counter number and increase the counter
| @Using session to save current visitor counter
--------------------------------------------------------------*/
function the_counter(){
global $file_name;
if(empty($file_name)){
return;
}
if($_SESSION['counter_number'] > 0 && $use_cookie == 1){
return $_SESSION['counter_number'];
}
$c = read_file($file_name);
if(empty($c)){
$c = 0;
}
$c = $c+1;
write_file($file_name,$c);
$_SESSION['counter_number'] = $c;
return $c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment