PHP fwrite 不使用附加模式更新文件

标签 php linux file fopen fwrite

以下代码可以运行,但不会更新其创建的文件的内容。

我可以看到文件内容已更改(大小增加),但当我从服务器下载文件时,它是空的。 该文件被 chmod 为 666 及其父目录。

它是一个运行 Apache 和 PHP 的 Linux 服务器。 我还尝试使用 fflush 来强制它刷新内容。

<?php

header("Location: http://www.example.com");
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
   fwrite($handle, $variable);
   fwrite($handle, '=');
   fwrite($handle, $value);
   fwrite($handle, '\r\n');
}

fwrite($handle, '\r\n');
fflush($handle);
fclose($handle);

?>

问题是什么?

谢谢!

最佳答案

我认为一个好的做法是使用 is_writable 检查文件是否可写,然后通过检查 fopen 返回的值来打开它,顺便说一句,您的代码是正确的。

试试这个:

$filename = "log.txt";
$mode = "a";
// 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, $mode)) {
         echo "Cannot open file ($filename)";
         exit;
    }

    foreach($_POST as $variable => $value) {
       fwrite($handle, $variable);
       fwrite($handle, '=');
       fwrite($handle, $value);
       fwrite($handle, '\r\n');
    }

    fwrite($handle, '\r\n');
    fflush($handle);
    fclose($handle);
    echo "Content written to file ($filename)";

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

关于PHP fwrite 不使用附加模式更新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24104577/

相关文章:

linux - 通过 cron 每分钟运行某个脚本会对任何事情产生不利影响吗?

php - Kohana session 表

异常类中的 php 父构造函数

php - vCalendar/iCal 在日历中显示空闲/忙碌

linux - 将时间与日期和字符串分开

linux - pp (PAR) 在哪里解压添加 (-a) 文件?

c# - 如何在 C# 中测试文件是否是 .Net 程序集

file - zip 文件和图像可以存储在 AppFabric 缓存中吗

python - 如何按字典顺序对文件路径进行排序? Python

PHP MySQLi 在插入时将文件重命名为行 ID