【问题标题】:(PHP) Can't write to file, can only read(PHP) 无法写入文件,只能读取
【发布时间】:2016-06-28 04:16:57
【问题描述】:

我是 PHP 新手,正在尝试练习读写文件。我能够读取文件并回显它,但我无法写入它。我已将目标文件和PHP文件的权限都修改为777(所有权限)。它不断回显文件内容而不更改它们,并且我没有收到任何错误。

<html>
<body>

<?php

//rewrite file
$f = fopen("test.txt", "w");
fwrite($f, $_POST["info"]);

//output file
$str = fread($f, filesize("test.txt"));
echo $str;

fclose($f);

?>

</body>
</html>

谢谢

【问题讨论】:

  • 返回什么错误?
  • 您确认$_POST['info'] 包含您认为的内容吗?您可以在 fwrite 行之前回显它以查看。
  • 您是否尝试在写入后关闭文件处理程序并查看是否有效?
  • 我认为您必须在再次阅读之前使用 fseek($f, 0) 重置您的指针。此外,要读写,您必须使用不同的诡计模式,例如 r+w+ w 的 - 参见相应的 php.net 手册
  • 我没有收到任何错误。我已经修复了文件模式。我认为这是一个权限问题,但我不确定将其设置为哪种权限模式。

标签: php file fopen server-side fwrite


【解决方案1】:

首先,您必须以读/写模式打开文件。看看fopen

然后,如果你想阅读你写的东西,你必须rewind文件指针。

这段代码应该可以工作:

<html>
<body>

<?php

//rewrite file
$f = fopen("test.txt", "r+");
fwrite($f, "Rewind command sets the position of the pointer at the begin of the file.");

if ( rewind($f) ) {
        //output file
        $str = fread($f, filesize("test.txt"));
        echo $str;
} else {
        echo "Error reading file";
}


fclose($f);

?>

</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-01
    • 2014-12-06
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多