I am trying to duplicate this: http://www.usagain.com/ <— On the left of their page they have a counter. I’ve literally tried everything I can think of but they have something going on in their PHP that I do not. My code is fairly straightforward:
HTML/CSS/Javascript/AJAX
<html>
<head>
<title>Counter</title>
<script language="javascript" src="../jquery1.6.js"></script>
<script type="text/javascript">
function addCommas(nStr) //http://www.mredkj.com/javascript/nfbasic.html -- Source
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\\d+)(\\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function getNum()
{
$.post('test.php', function(data){
$('#counter').html(addCommas(data));
})
}
setInterval(getNum, 1000);
</script>
<style type="text/css">
#counterContainer{color: #52504D;font-family:Verdana, Geneva, sans-serif;font-weight:bold;font-size:15px;position:relative;top:22px;}
#counter{color: #1E7EC8; font-size: 25px;letter-spacing:1px;}
</style>
</head>
<body onload="getNum()">
<div id="counterContainer">
<div id="counter"><!--Counter Goes Here, Do Not Disturb--></div>
</div>
</body>
</html>
And my PHP just reads the number in the file, updates the number, ehcos it back to AJAX, and updates the file. Here’s the code:
<?php
$fp = fopen("staticNum.txt", "r+");
flock($fp, LOCK_EX);
$num = fgets($fp, 11);
$num = intval($num)+1;
echo $num;
fseek($fp, 0, SEEK_SET);
fputs($fp, "$num");
flock($fp, LOCK_UN);
fclose($fp);
?>
The problem is if 2 people view the page at the same time, the number will increment by 2 instead of 1. If 3 people view it the number will increment by 3 and so on. How do I prevent this and keep it incrementing by 1 no matter what?