我有一个要保存的变量它是:
$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 job,它将不起作用。
编辑
$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
。