Home > Programming > PHP WebCounter


PHP Web Counter

Simple counter that increments per session. That is, the counting variable is only incremented if a new browser instance calls the page in which the counter sits.

on http://www.php.net.

Code

If you copy the code, take care that there are NO SIGNS before the first "<?php" tag in the php file. The code has to be interpreted before anything is sent to the user. Also be sure that the rights of hits.txt are properly set.

See how it works.

<?php

// start session
session_start();

// increments hit counter if user opens new session

$hitfile = "hits.txt";

// if hits is not registered we register it and increment the number in hits.txt
if ( $_SESSION['hits'] != 1 )
{
// create global session variable hits
$_SESSION['hits'] = 1;

// count hit
$fp=fopen($hitfile,"r");
$hitcount=fread($fp,filesize($hitfile));
fclose($fp);

//add one to the current hit count
$hitcount=$hitcount+1;

//write the new value back to the file
$fp=fopen($hitfile,"w");
fwrite($fp,$hitcount);
fclose($fp);
}


?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>PHP Web Counter</TITLE>
<META content="text/html; charset=iso-8859-1" http-equiv=Content-Type>
</HEAD>

<?php

// function that reads hit.txt

function readHit(){
//open the hitfile
$hitfile = "hits.txt";
$fp=fopen($hitfile,"r");
$hitcount=fread($fp,filesize($hitfile));
fclose($fp);
return $hitcount;
}

?>

<BODY>
Visitor #
<?php print(readHit());?>.
</BODY>
</HTML>


1350 people visited this page.