简体   繁体   English

使用PHP将文本写入.txt文件

[英]Writing text to .txt file using PHP

So I have page.txt which looks like this: 所以我有page.txt看起来像这样:

<textarea name="msg" rows="1"></textarea>
<form id="post" name="post" action="storeText.php" method="post">
    <input class="button" type="submit" value="Set news now"/>
</form>

I also have storeText.php which looks like this: 我也有如下所示的storeText.php:

<?php       
$filename = 'posts.txt';
$msg = (isset($_POST['msg']) ? $_POST['msg'] : null);

    // Let's make sure the file exists and is writable first.
    if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
        echo "Cannot open file ($filename)";
        exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $msg) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($msg) to file ($filename)";

    fclose($handle);

    } else {
    echo "The file $filename is not writable";
    }
?>

Now it should write the text onto posts.txt but it always says "Success, wrote () to file...". 现在,它应该将文本写到posts.txt上,但始终显示“成功,将()写入文件...”。 Notice the empty parenthesis which should have my input. 请注意应该有我的输入的空括号。

Any ideas? 有任何想法吗? Thanks! 谢谢!

<textarea name="msg" rows="1"></textarea>
<form id="post" name="post" action="storeText.php" method="post">
    <input class="button" type="submit" value="Set news now"/>
</form>

If the textarea is outside of the form block it won't be sent. 如果textarea在表单块之外,则不会发送。 So your html should look like: 因此,您的html应该如下所示:

<form id="post" name="post" action="storeText.php" method="post">
    <textarea name="msg" rows="1"></textarea>
    <input class="button" type="submit" value="Set news now"/>
</form>

Your <textarea> element is outside of your <form> tags. 您的<textarea>元素在<form>标记之外。

<textarea> should either go inside the form tags or you need to specify a form attribute to link the input to a form eg <textarea form="myForm"> (the latter may not work in older browsers, though, best to put it inside the <form> tag if you can). <textarea>应该放在表单标签内,或者您需要指定form属性以将输入链接到表单,例如<textarea form="myForm"> (后者可能在较旧的浏览器中不起作用,但是最好将它放在在<form>标记内)。

That's why your $_POST['msg'] is null 这就是为什么您的$_POST['msg']为空

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM