Question

What's the best way to make a hit counter using PHP or MySQL? I'm having several file overwrite issues using the PHP flock() function, because it isn't working as it should. It tries to write the same file increasing the same variable at the same time of another process, but the variable value increases only by one instead of two, causing loss of a hit counted. I tried using a MySQL database as a counter but it misses more hits than with the method described above.

Here's the code I tried using the flock function:

while(!$fp=fopen($filename,"a+"))
{
    usleep(100000);
}
while(!flock($fp,LOCK_EX))
{
    usleep(100000);
}
while(!include($filename))
{
    usleep(100000);
}
ftruncate($fp,0);
rewind($fp);
$$varname=$newval;
//$text="text changes depending on the $type value";
fwrite($fp,$text);
flock($fp,LOCK_UN);
fclose($fp);

As I just said, the script works fine until it's run two times at the same time.

What do I have to do in order to count every single hit?

Was it helpful?

Solution

If all you need the database for is tracking hit counts, then you'd be better off using a file as you are doing now. What you are missing is flushing the file to disk before releasing the lock. See http://nz.php.net/flock

while(!$fp=fopen($filename,"a+")) usleep(100000);
while(!flock($fp,LOCK_EX)) usleep(100000);
while(!include($filename)) usleep(100000);

ftruncate($fp,0);
rewind($fp);
$$varname=$newval;
//$text="text changes depending on the $type value";
fwrite($fp,$text);

fflush($fp);

flock($fp,LOCK_UN);
fclose($fp);

OTHER TIPS

/***Increment charge code***/
        $fp = fopen('/var/www/html/live/vodcount.txt', 'c+');
        flock($fp, LOCK_EX);
        $count = (int)fread($fp, filesize('/var/www/html/live/vodcount.txt'));
        ftruncate($fp, 0);
        fseek($fp, 0);
        fwrite($fp, $count + 1);
        flock($fp, LOCK_UN);
        fclose($fp);
        $arr['charge_code'] = "aadata".$count;
        /***Increment charge code***/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top