douxi4287 2014-06-08 09:00
浏览 74
已采纳

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

The following code is working but it doesn't update the contents of the file it created.

I can see that the file contents have changed (the size increased) but when I download the file from my server it's empty. the file is chmod to 666 and its parent directory as well.

its a linux server running Apache and PHP. I've also tried using fflush to force it to flush the contents.

<?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, '
');
}

fwrite($handle, '
');
fflush($handle);
fclose($handle);

?>

what is the problem?

Thanks!

  • 写回答

1条回答 默认 最新

  • douyu7210 2014-06-08 09:17
    关注

    I think a good practice is to check if a file is writable with is_writable then if it can be opened by checking the value returned by fopen, by the way your code is right.

    Try this:

    $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, '
    ');
        }
    
        fwrite($handle, '
    ');
        fflush($handle);
        fclose($handle);
        echo "Content written to file ($filename)";
    
    } else {
        echo "The file $filename is not writable";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作