I'm writing , just to experiment , a web page daily hit counter using PHP.
Multiple access from the same browser during the same day should be counted as 1, in order to do that I'm using cookies.
The problem is that , before the browser gets the cookie , the script can be executed in parallel multiple times without any thread finding the cookie , therefore the counter does not work as expected.
So how can I avoid the script is executed in parallel to serve requests coming from the same browser ?
thanks.
Here's the example:
note that to make debugging easier the day is now 1 minute long :D,
the counter is the second value from the left.
http://ralfralf.atwebpages.com/index2.php
here's the code: (can someone help me making it look readeable?) :D
<?php
$visitsfile = file("visits.txt");
if( ! isset($_COOKIE["visitor"] ) )
{
$rest = time() % 60;
$rest1 = 60 - $rest;
setcookie("visitor" , "visitor" , time() + $rest1 );
$bolval = 0;
if( sizeof($visitsfile) > 0)
{
$i = sizeof($visitsfile) - 2;
$val = floor( ( intval( substr( $visitsfile[$i] , 0 , - 1) ) / 60 ) ) - floor( ( time() / 60 ) ) ;
if( $val == 0 )
{
$visitsfile[$i+1] = intval( substr( $visitsfile[$i + 1] , 0 , - 1) ) + 1 . "
";
$bolval = 1;
}
}
if( sizeof($visitsfile) == 0 || !$bolval)
{
if(sizeof($visitsfile) == 0)
{
$i = 0;
}
else
{
$i = sizeof($visitsfile);
}
$visitsfile[$i] = time() . "
";
$visitsfile[$i+1] = "1
";
}
$fp = fopen("visits.txt", "w");
if (flock($fp, LOCK_EX))
{
$i = 0;
while($i < sizeof($visitsfile))
{
fwrite($fp, $visitsfile[$i] );
$i++;
}
flock($fp, LOCK_UN);
}
fclose($fp);
}
$n = sizeof($visitsfile);
if(! isset($_COOKIE["visitor"]))
{
echo intval( substr( $visitsfile[$n - 2] , 0 , - 1) ) . " " . (intval( substr( $visitsfile[$n - 1] , 0 , - 1) ) - 1 ) ;
}
else
{
echo intval( substr( $visitsfile[$n - 2] , 0 , - 1) ) . " " . intval( substr( $visitsfile[$n - 1] , 0 , - 1) ) ;
}
?>