【问题标题】:Saving data from HTML form on server?在服务器上保存 HTML 表单中的数据?
【发布时间】:2017-09-04 13:41:30
【问题描述】:

如何在服务器上保存 HTML 表单中的数据?

这是我的代码:

<form action="?action=save" name="myform" method="post">

<textarea class="textBox" name="mytext"> </textarea>
<input type="submit" class="save" value="save"/>

提前致谢。

【问题讨论】:

    标签: php html css forms


    【解决方案1】:

    您需要更改操作名称以指向 PHP 代码所在的位置。我将我的 PHP 代码与我的 HTML 放在同一页面上,并将操作更改为 save.php(这是我的 PHP 所在的文件名)。

    这是我的 save.php 文件,一切都在其中。

    <?php
    // Check if form is submitted and we have the fields we want.
    if(isset($_POST["mytext"]))
    {
    	$file = "data.txt";
    	$text = $_POST["mytext"];
    
    	// This file will create a data.txt file and put whatever is in the POST field mytext into the text and put a new line on the end.
    	// The FILE_APPEND allows you to append text to the file. LOCK_EX prevents anyone else from writing to the file at the same time.
    	file_put_contents($file, $text . "\r\n", FILE_APPEND | LOCK_EX);
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    	<title>Save POST Data</title>
    </head>
    <body>
    
    <form action="save.php" name="myform" method="post">
    
    <textarea class="textBox" name="mytext"></textarea>
    <input type="submit" class="save" value="save"/>
    
    </body>
    </html>

    【讨论】:

      【解决方案2】:

      最简单的方法是在 save.php 上设置操作并放在这个文件中

      <?php 
          if(isset($_POST)){
              file_put_contents('file.txt', json_encode($_POST));
          }
      

      【讨论】:

      • 您也需要一个 \r\n 来在 .txt 中创建新行。
      【解决方案3】:

      您可以通过js处理提交事件,并通过ajax或fetch将数据发送到服务器。然后在您的服务器端,构建一个 API 来捕获请求并将数据存储在数据库或您想要存储数据的任何文件中。

      最好的

      【讨论】:

        猜你喜欢
        • 2022-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-20
        • 1970-01-01
        • 2011-09-03
        • 2019-06-26
        相关资源
        最近更新 更多