【问题标题】:fopen fread and fwrite troublefopen fread 和 fwrite 麻烦
【发布时间】:2015-01-11 15:18:27
【问题描述】:

我试图让用户在文本框中写一些东西。然后将文本写入名为“list.txt”的文件中的新行。然后我希望在网站上阅读整个文件。这样它就像一个聊天室或其他东西。问题是,现在它告诉我“无法打开文件”。我已经检查了文件的权限,并且每种类型的用户都具有完全访问权限。 List.txt 也与 php 文件位于同一目录中。此外,当它能够打开文件时,它不会将其写入新行。我知道这可以使用 "\n" 或 PHP.EOL 来完成,但它们似乎都不起作用,有时它们会阻止网站本身运行。请帮我弄清楚是怎么回事,谢谢。

<html>

<p>
<form name="form1" method="post" action="test.php">
<input name="text" type="text">
<input type="submit" value="send" method="post">
</p>

<p>
<?php


$file = fopen("list.txt") or die ("Unable to open file!");
$text = $_POST['text'];//where the hell do you put the new line indicator: "\n"//

fwrite($file, $text) or die ("Cannot write!");


$print = fread($file,filesize("list.txt", "a+"));
fclose($file);
echo $print;


?>


</p>


<?php //figure out how to make this a button that clears the file
/*
$fp = fopen("list.txt", "r+");
// clear content to 0 bits
ftruncate($fp, 0);
//close file
fclose($fp);*/
?>


</html>

【问题讨论】:

  • 为什么不使用 file_put_contents
  • 看起来您在 filesize() 函数中使用了访问修饰符。你只需要一个参数,文件名。

标签: php fwrite fread


【解决方案1】:

使用file_put_contents...

   $file = 'list.txt';
    $content =  $_POST['text']."\n";
    // Write the contents to the file, 
    // using the FILE_APPEND flag to append the content to the end of the file
    file_put_contents($file, $content, FILE_APPEND);

根据文档

此函数与调用 fopen()、fwrite() 和 fclose() 相同 依次将数据写入文件。

如果文件名不存在,则创建文件。否则,该 现有文件将被覆盖,除非设置了 FILE_APPEND 标志。

【讨论】:

  • 这很有帮助。谢谢。我仍然有一个问题,因为我使用 $_POST 作为内容,我如何确保它写入一个新行?
  • 这就是我一直在尝试的。似乎它仍然写在同一行。在文件和网站上读回时都在文件中
  • 我认为它在每个字符串之间添加了一个空格,但不是换行符
  • 不可能...我运行了这段代码并测试了..每次调用php文件时都会添加一个新行...你的问题是什么
  • 会发生什么:
【解决方案2】:

您的问题是您的文件将在 php 写入内容时被锁定。

如果你想同时写,那么你有很短的时间无法访问你的文件。这就是基于文件的解决方案的大问题。数据库引擎就是为此而生的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多