【问题标题】:Troubleshoot PHP fwrite: overwrite int for counterPHP fwrite 疑难解答:overwrite int for counter
【发布时间】:2011-11-02 03:31:45
【问题描述】:

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

这个小曲子是实现计数器的门户。问题是,它运行,但没有正确增加。文件 count.txt 保留最初的 0 值(在第一行)并在第二行连续添加 1(每次运行时,如“1111”)。每次生成的回显都是“当前计数:1”。

我看过的一些教程,fopen('r') 原始添加/回显,然后再次 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);
?>

【问题讨论】:

  • 在写之前先找文件的开头(我想fseek)。

标签: php fopen fwrite fread


【解决方案1】:

尝试使用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);
?>

【讨论】:

    猜你喜欢
    • 2021-07-19
    • 2013-10-22
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 2018-09-06
    相关资源
    最近更新 更多