如何使用PHP将表单数据保存到本地文本文件?

时间:2018-04-30 14:41:06

标签: php html5 forms

我有一个表单,我想在其中捕获用户的名称和电子邮件并将其存储在文本文件中。我不确定这是我的代码还是我必须在特定的地方保存我的脚本。单击提交按钮时,出现“未找到404文件或目录”的错误。我的客户端通过ftp上传它们,所以我无法检查它是否在本地运行。 PHP脚本(process-form-data.php)和文本文件(formdata.txt)保存在公共HTML文件夹中。我对PHP很陌生,很抱歉,如果这是一个愚蠢的问题。任何关于我做错的帮助以及上传文件的过程都将非常感谢,谢谢!

   <form name=”web_form” id=”web_form” method=”post” action=”process- 
    form-data.php”>

     <label for="exampleInputEmail1"><h3 style="color: #eee; margin: 0; 
     font-weight: 400;">Request Information</h3></label>

     <input type="text" name=”name” class="form-control" id="name" 
      placeholder="Your Name">

     <input type="text" class="form-control" name=”email” id=”email” 
      placeholder="youremail@domain.com">

     <button type="submit" name=”s1″ id=”s1″ value="submit" class="btn 
     btn-primary btn2">Submit</button>
  </form>


<?php
 $name = $_POST[‘name’];
 $email = $_POST[’email’];
 $fp = fopen(”formdata.txt”, “a”);
 $savestring = $name . “,” . $email . “n”;
 fwrite($fp, $savestring);
 fclose($fp);
 echo “<h1>You data has been saved in a text file!</h1>”;
?>

1 个答案:

答案 0 :(得分:0)

你应该注意用你的html代码写的双引号(“”)

<form name='web_form' id='web_form' method='post' action=''>

     <label for="exampleInputEmail1"><h3 style="color: #eee; margin: 0; 
     font-weight: 400;">Request Information</h3></label>

     <input type='text' name='name' class="form-control" id="name" 
     placeholder="Your Name">

     <input type="text" class="form-control" name='email' id='email' 
     placeholder="youremail@domain.com">

     <button type="submit" name='s1' id='s1' value="submit" class="btn btn- 
     primary btn2">Submit</button>
  </form>

此代码将电子邮件和姓名写入文本文件

<?php
    if (isset($_POST['s1'])) {
      echo $_POST['name'];
      echo $_POST['email'];

      $myfile = fopen("data.txt", "w") or die("Unable to open file");
      $name = $_POST['name']."\n";
      fwrite($myfile, $name);

      $email = $_POST['email']."\n";
      fwrite($myfile, $email);
      fclose($myfile);
    }
  ?>