在 html 页面的文本区域中输入的文本未保存在文本文件中


Text entered in TextArea of html page not saving in text file.

我正在尝试将以HTML形式输入的数据保存在文本文件中。我正在使用 php 脚本来执行此操作。当我单击提交按钮时,它不会将数据保存在文本文件中。有人可以告诉我这里出了什么问题。

下面是代码片段 -

网页表单 -

<form id="post" name="post" method="post" action="input.php">
    Name: <input type="text" name="name"><br>
    Text: <textarea rows="50" cols="85" name="blogentry"></textarea>
    <input class="button" type="submit" value="Submit">
</form>

PHP - (输入.php)

<html>
   <head></head>
   <body>
   <?php 
   // variables from the form
   $name = $_POST['name'];
   $blogentry = $_POST['blogentry'];
    // creating or opening the file in append mode
    $dataFile = "data.txt";
    $fh = fopen($dataFile, 'a');
    // writing to the file
    fwrite($fh, "Name - " . " " . $name . " " . "'n");
    fwrite($fh, "Blog - " . " " . $blogentry . " " . "'n'n");
    fclose($fh);
    ?>
   </body>
</html>

在这种情况下,查明问题很有用。也许表单没有提交你的文本区域,或者你的PHP没有收到它,或者可能是你对值所做的事情有问题。

如果您在像 Firebug 这样的检查器中查看表单提交,您是否在请求中看到正在提交的文本区域的内容?

如果在代码中执行var_dump($_POST),是否会看到从表单提交的所有值?

你能试试这个吗,

   if(isset($_POST['name']) && isset($_POST['blogentry'])){
            $name = $_POST['name'];
            $blogentry = $_POST['blogentry'];
            // creating or opening the file in append mode
            $dataFile = "data.txt"; // make sure the directory path is correct and permission of the folder
            $fh = fopen($dataFile, 'w');    // writing to the file
            $stringData = "Name - " . " " . $name . " " . "'n";
            $stringDataBlog = "Blog - " . " " . $blogentry . " " . "'n'n";
            fwrite($fh, $stringData);                  
            fwrite($fh, $stringDataBlog);  
            fclose($fh);                
  }

你的代码没有错误。如果数据.txt存在并有权在其上写入,则代码应该可以工作。请检查文件权限。

我刚刚遇到了同样的问题。您需要将带有表单 ID 的表单标记添加到文本区域元素。从上面更正您的代码::

<form id="post" name="post" method="post" action="input.php">
    Name: <input type="text" name="name"><br>
    Text: <textarea rows="50" cols="85" name="blogentry" form="post"></textarea>
    <input class="button" type="submit" value="Submit">
</form>

那么它应该可以工作。