首页 > 解决方案 > PHP / Apache fwrite 更新修改日期但不写入

问题描述

使用 PHP fwrite 简单示例,代码更新文件(修改日期/时间更改)但没有写入任何内容。我没有错误。我得到:

成功,将(添加到文件中)写入文件(./errors/test.txt)

然而该文件是空的,并且日期修改了更改 - 就好像它被写入了一样。

我在 PHP 7.0/Apache2 Debian (Raspberry Pi B) 上。我开始将文件权限设置为 755 并将其更改为 777,但没有成功。所有者是 www-data - 我已经尝试过 root 和另一个所有者 - 都失败了,因为您需要将所有者设置为 www-data 才能写入。

我已经尝试了./errors/test.txterrors/test.txt - 它没有区别。

我试过fopen($filename, 'a')fopen($filename, 'w')并且都产生相同的结果。

<?php
$filename = './errors/test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

标签: phpfwrite

解决方案


在fwrite函数中添加长度参数对我有用。

用这个替换写代码。这可能会奏效。

// Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent,strlen($somecontent)) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

推荐阅读