我陷入了一个小问题。我有一个 php 页面:
索引.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
代码有问题吗?
它在带有 Apache 的 Ubuntu 18 上运行,具有权限的文件是
-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
答案将不胜感激