1

我陷入了一个小问题。我有一个 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

答案将不胜感激

4

1 回答 1

3

在 ftruncate 之后使用 Rewind(需要一些工作来隔离它)

    ftruncate($fp, 0);      // truncate file
    rewind($fp); //rewind the pointer

或者您可以只使用rewind而不是ftruncate,这似乎是\0空字节的原因。两者都做似乎毫无意义,就好像你在倒带后写它无论如何都会擦除文件(除非你使用a+追加)......

查看文档的第一个示例同时使用两者。

http://php.net/manual/en/function.ftruncate.php

来自 PHP.net

<?php
$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);

echo fread($handle, filesize('output.txt'));

fclose($handle);
?>

即使没有解释原因......我只是使用rewind(),但我总是很懒,所以我努力编写我需要的最少代码,因为我写了很多代码。

另一种解决方案

使用前修剪文件的内容intval

  $counter = intval(trim(fread($fp, filesize("counter.txt"))));

在记事本++

  [null][null]1

在此处输入图像描述

无论如何,这是一个有趣的...谢谢!

于 2019-02-13T22:35:54.760 回答