繁体   English   中英

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

[英]Writing text to .txt file using PHP

所以我有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>

我也有如下所示的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";
    }
?>

现在,它应该将文本写到posts.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>

如果textarea在表单块之外,则不会发送。 因此,您的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>

您的<textarea>元素在<form>标记之外。

<textarea>应该放在表单标签内,或者您需要指定form属性以将输入链接到表单,例如<textarea form="myForm"> (后者可能在较旧的浏览器中不起作用,但是最好将它放在在<form>标记内)。

这就是为什么您的$_POST['msg']为空

暂无
暂无

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

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