你好,
我给自己写了一个PHP实验。此脚本计算用户单击带有特定类别(id =“ link_1”,class =“ heart”)的按钮的次数
每次单击时,脚本都会读取一个txt文件,找到正确的ID,然后在该ID的号码上添加+1,如下所示:
#counte_me.php
$file = 'count_me.txt'; // stores the numbers for each id
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
fclose($fh);
file_put_contents($file, $lines, LOCK_EX);
结果
# count_me.txt
hello_darling||12
这非常好用。问题是,有时我发现自己盯着一个空的count_me.txt!
实际上不知道它何时或如何发生,但确实如此。我开始逐渐增加并发生,有时会更快,有时会稍后。它可能在我到达10或200或320或两者之间的任何途中。它完全是随机的。
让我发疯。我经验不足,但这就是为什么我要玩这个东西。
有人知道我在这里做错了什么,这样的文件就被转储了吗?
更新1 到目前为止,Oluwafemi Sule的建议正在起作用,但是我必须从file_put_contents中删除LOCK_EX才能起作用,否则就不能了。
// NEW LINE ADDED
if (!empty($lines)) {
file_put_contents($file, $lines);
}
答案 0 :(得分:0)
$lines
is initially set to an empty string and only updated on the following condition.
if(!empty($item)) {
# and so on and so on
}
And finally at the end,
file_put_contents($file, $lines, LOCK_EX);
The reason that $lines
still remains set to the initial empty string happens when item
is empty. Remember the newline added from "$item||$num\r\n"
, there could be more than a single line added there(I won't put it past a text editor to add a new line to end that file .)
I suggest to only write to the file when $lines
isn't empty.
if (!empty($lines)) {
file_put_contents($file, $lines, LOCK_EX);
}