只是试图计算按钮被点击的次数,将其记录到文件中,以便适用于所有人。它正在读取文件,但没有写入。想法?用PHP计算按钮点击次数
<form action='' method="post">
<input type="submit" name="submit" value="Tweet it!" onclick="genTweet()"/>
</form>
<br>
<?php
$f = fopen('counter.txt', 'r+'); // use 'r+' instead
flock($f, LOCK_EX); // avoid race conditions with concurrent requests
$total = (int) fread($f, max(1, filesize('counter.txt'))); // arg can't be 0
/*if someone has clicked submit*/
if (isset($_POST['submit'])) {
rewind($f); // move pointer to start of file so we overwrite instead of append
fwrite($f, ++$total);
}
fclose($f);
?>
This button has been clicked <?php echo $total; ?> times.
我会避免使用此文件。我会切换到数据库解决方案。如果两个人同时点击该按钮,可能会出现差异。 – QuinnFTW 2014-08-30 20:57:25
检查以确保文件具有正确的写入权限。通常644会做,但作为最后的手段,尝试777.虽然不推荐777,但你可以尝试两种。 – 2014-08-30 21:09:25
@QuinnFTW虽然我同意使用DB,但OP使用文件锁定“LOCK_EX”。 – 2014-08-30 21:12:50