fopen fread和fwrite麻烦

时间:2015-01-11 15:18:27

标签: php fwrite fread

我正在尝试让用户在文本框中写一些东西。然后将文本写入名为“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>

2 个答案:

答案 0 :(得分: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()相同   先后将数据写入文件。

     

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

答案 1 :(得分:0)

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

如果您想同时写信,那么您很快就无法访问您的文件。这是基于文件的解决方案的重大问题。数据库引擎就是为此而创建的。

相关问题