Zend - The PHP Company




Counters

Add Code


Cookie Counter  

Type: code fragment
Added by: magfoor
Entered: 30/05/2002
Last modified: 06/12/2001
Rating: **** (6 votes)
Views: 10926
A simple counter using cookies by Magfoor


<?
//to use this code you need to create a text file named 'count.txt in the same directory
//check whether the cookie exists or not
$counted $HTTP_COOKIE_VARS["Counter"];
//if it doesn't exists then
if($counted==""){
//create the cookie
    
setcookie("Counter","Counted");
//open the file in reading mood at first
    
$fp=fopen("count.txt","r")or die ("Can't open file");
//get what is written on the file
    
$counted=fgets($fp,1024);
//close the file
    
fclose($fp);
//now add 1 to the counted variable 
    
$counted=$counted+1;
//now overwrite the file with the new counted value
    
$fp=fopen("count.txt","w");
    
fwrite($fp,$counted);
    
fclose($fp);
    print 
"The page has been visited $counted times";
//if the cookie exixts then don't do anything except showing th previous value
}else{
    
$fp=fopen("count.txt","r")or die ("Can't open file");
    
$counted=fgets($fp,1024);
    
fclose($fp);
    print 
"The page has been visited $counted times";
}
?>


Usage Example


See the example


Rate This Script





Search



This Category All Categories