当保存文本区域的内容到文件时,不写


fwrite not fwriting when saving contents of a textarea to a file

我正在制作一个在线文本编辑器-只是一个简单的我自己的东西。我试图编写代码来保存文本区域的内容到一个文件-首先文件被打开到文本区域(它工作良好),然后我想保存编辑的文本。写不出来了。下面是重要的代码(我为混乱道歉,这对我和PHP来说是非常早期的):

<form method="post" action="<?php echo $_SERVER['$PHP_SELF'];?>">
<textarea rows="30" cols="80" name="textdata"><?=$contents?></textarea>
<br />
<?php
$newcontents = $_POST["textdata"];
$openedfile = fopen($filename, "r");
fwrite($openedfile, "hello");
?>
<input type="submit" name="save" value="Save Changes" />
</form>

这是因为您使用r标志在readonly模式下打开文件:

$openedfile = fopen($filename, "r");
 -------------------------------^

您应该使用r+, wa(追加)标志。

更多标志/信息请参见文档

 fopen($filename, "r");

仅用于读取…

使用

fopen($filename, "r+");

您以只读模式打开了文件句柄。

$openedfile = fopen($filename, "r");您打开文件为只读模式,使用r+代替r

我建议您查看file_put_contents,因为它简化了所有fwrite, handlefclose的内容。通常使用这个函数非常非常容易。摘自文档:

$file = $filename;
$text .= "Hello'n";
file_put_contents($file, $text);