我的 fopen() 有什么问题 PHP

What is wrong with my fopen() PHP

我有这个要保存的变量:

$counter = $counter['counter']++;

让它在我刷新页面时递增。 因此,我决定使用 fopen,覆盖 $counter 变量,然后保存它。 我还是初学者,不知道fopen、fgets、fclose是怎么工作的。

所以我写了这样的东西。

$fp = fopen("file.php","r");
fwrite($fp, $counter);
fclose($fp);

所以我想打开文件(file.php)(我正在编写此代码的文件,仅供参考),然后在变量递增后覆盖它,然后通过关闭保存它。

但代码似乎并不想工作,变量似乎也不想增加。 我究竟做错了什么? 我想把这个 $counter 放在不同的文件中并从那里提取变量吗?

仅供参考:我不想使用 session_start() 和 $_SESSION,因为我正在使用 cron 作业,它不会工作。

编辑

$result = mysql_query('SELECT MIN(ID) AS min, MAX(ID) AS max FROM ytable') or exit(mysql_error()); 
$row = mysql_fetch_assoc($result); 

if($counter['counter'] < $row['max']){
    if (isset($counter['counter'])){
        $counter = $counter['counter']++;

    }else{
            $counter = $counter['counter'] = 0;
        }
 }

这是给那些困惑的人的更多代码

你可以这样阅读文件。使用先前的计数器打开文件并获取计数器,像这样递增它

$counter = readfile("file.php");
$counter++;

要写入文件,像这样以写入模式打开文件

$fp = fopen("file.php","w");
fwrite($fp, $counter);
fclose($fp);

这是您要找的结果吗?

正如 chris85 所建议的,数据库用于此类情况。最好使用数据库而不是文件处理。

假设您有 file.txt,其中包含 5。在同一个目录中,您有 script.php;这个文件会有

$counter = file_get_contents('file.txt'); // this takes in whatever value is in the file e.g in this case '5'
$counter++; // increment the value by 1 so we are now at 6
file_put_contents('file.txt', $counter); //write the value '6' back to the file

file.txt 在第一次加载后会有 6