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

时间:2014-02-25 03:14:33

标签: php html post

所以我的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,但它总是说“Success,write()to file ...”。注意应该有我输入的空括号。

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:0)

<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>

答案 1 :(得分:0)

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

<textarea>应该放在表单标记内,或者您需要指定form属性来将输入链接到表单,例如<textarea form="myForm">(后者可能无法在较旧的浏览器中使用,但如果可以的话,最好将其放在<form>标记内。

这就是你的$_POST['msg']为空

的原因