PHP hitcounter 在每次命中的数字前添加符号

PHP hitcounter adds symbol before digit for each hit

我遇到了一个小问题。我有一个 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一次后,textfile内容变成了^@^@1,之后又变成了^@^@^@1

我要的是0变成1,然后2

代码有问题吗?

是运行在Ubuntu18,用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

不胜感激

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

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

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

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

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()但是我总是很懒所以我尽量写最少的代码,因为我写了很多代码。

另一种解决方案

Trim 使用前文件的内容 intval

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

在记事本++中

  [null][null]1

总之很有趣...谢谢!