【发布时间】:2023-05-09 16:51:01
【问题描述】:
我遇到了一个小问题。我有一个 php 页面:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<?php
include( 'counter.php' );
?>
</body>
</html>
还有文件counter.php
<?php
$fp = fopen("counter.txt", "r+");
if(!$fp){
error_log("Could not open counter.txt");
exit();
}
if(!flock($fp, LOCK_EX)) { // acquire an exclusive lock
error_log("Could not lock");
}
else{
$counter = intval(fread($fp, filesize("counter.txt")));
$counter++;
echo $counter;
ftruncate($fp, 0); // truncate file
fwrite($fp, $counter); // set your data
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
}
fclose($fp);
?>
以及文件counter.txt,其内容为“0”(0)
运行一次index.php后,文本文件内容变为^@^@1,之后变为^@^@^@1
我想要的是0变成1,然后是2
代码有问题吗?
它在 Ubuntu 18 上运行,带有 Apache,并且具有权限的文件是
-rw-rw-r-- 1 emanuel www-data 559 Feb 13 21:56 counter.php
-rw-rw-r-- 1 emanuel www-data 11 Feb 13 22:51 counter.txt
-rw-rw-r-- 1 emanuel www-data 128 Feb 13 22:50 index.php
drwxrwxr-x 2 emanuel www-data 4096 Feb 12 14:55 software
不胜感激
【问题讨论】:
-
就我个人而言,我会使用
file_get_contents和file_put_contents与LOCK_EX标志。 - 但那是我。它还会将您的代码减少一半。 -
the textfile content becomes ^@^@1,echo 语句是怎么说的? -
谢谢@ArtisticPhoenix,回声说“1”
-
您是否 100% 确定没有其他代码正在修改此文件?
-
此外,您应该将
$counter显式转换为字符串(string) $counter,并且可以使用declare(strict_types=1)约束。如果文件不存在,则进一步创建文件,并在文件为空时使用$counter = ($fsize = filesize("counter.txt")) ? intval(fread($fp, $fsize)) : 0;初始化计数器。否则fread由于大小为零而引发错误。
标签: php fopen fwrite flock hitcounter