fopen fread and fwrite trouble


fopen fread and fwrite trouble

我试图让用户在文本框中写一些东西。然后将文本写入名为"list.txt"的文件的新行上。然后我希望在网站上阅读整个文件。这样它就像一个聊天室或其他东西。问题是,现在它告诉我"无法打开文件"。我已经检查了文件的权限,每种类型的用户都具有完全访问权限。List.txt 也与 php 文件位于同一目录中。此外,当它能够打开文件时,它不会将其写入新行。我知道这可以使用"'"或 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 ...

   $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标志,否则将覆盖现有文件。

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

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