PHP fwrite疑难解答:覆盖计数器的int

时间:2011-11-02 03:31:46

标签: php fopen fwrite fread

快速免责声明:这是我的第二个PHP项目,也是我使用的第一个脚本语言。

这个小小的小调是实施计数器的门户。问题是,它运行,但没有正确增加。文件count.txt保留初始0值(在顶行)并连续地向第二行添加1(每次运行时,如“1111”)。产生的回声每次都是“当前计数:1”。

我见过的一些教程,fopen('r')原点添加/ echo out,然后fopen('w')再次保存。我试过了,绝对有效。我正在探索它是否可以巩固。任何洞察它为什么跳到第二行或一般建议的人都非常感激。

<?php
$countfile = "count.txt";
$counthandle = fopen($countfile, "r+");
$count = intval(@fread($counthandle, filesize($countfile)));
$count++;
echo "Current count: ";
echo $count . "<br/>\n";
fwrite($counthandle, $count);
fclose($counthandle);
?>

1 个答案:

答案 0 :(得分:0)

尝试使用file_get_contentsfile_put_contents

<?php
$countfile = 'count.txt';
$count = intval(file_get_contents($countfile));
$count++;
printf ("Current count:<br />%s", $count);
file_put_contents($countfile, $count);
?>