Jason Stackhouse
Jason Stackhouse

Reputation: 1836

Counter code not counting properly

Here is the code I use for counting on my site. The problem is that sometimes it does not count all the clicks.

<?php

//acquire file handle
$fd=fopen('counter.txt','c+b');
if (!$fd) die("");

//lock the file - we must do this BEFORE reading, as not to read an outdated value
if (!flock($fd,LOCK_EX)) die("");

//read and sanitize the counter value
$counter=fgets($fd,10);
if ($counter===false) die("");
if (!is_numeric($counter)) {
    flock($fd,LOCK_UN);
    die("");
}

//increase counter and reconvert to string
$counter++;
$counter="$counter";

//Write to file
if (!rewind($fd)) {
    flock($fd,LOCK_UN);
    die("");
}
$num=fwrite($fd,$counter);
if ($num!=strlen($counter)) {
    flock($fd,LOCK_UN);
    die("");
}

//Unlock the file and close file handle
flock($fd,LOCK_UN);
fclose($fd);

?>

I am not sure what to do now. Is there a better way of writing my code or should I use another technique?

Upvotes: 0

Views: 108

Answers (1)

Tchoupi
Tchoupi

Reputation: 14681

As per chat discussion with OP and after trying different approaches, we reached the conclusion that it would be more convenient to use a database to implement a click counter and handle concurrent access to the data.

mysql_connect(HOSTNAME, USERNAME, PASSWORD); 
mysql_select_db(DATABASE); 
mysql_query('UPDATE tbl_click SET click = click + 1'); 

Upvotes: 1

Related Questions