我想将表单标签中的新数据存储到php文件中?

时间:2016-01-01 08:02:27

标签: php forms

我正在尝试创建一个PHP页面,它会向用户询问三件事。电子邮件,名字和姓氏。我希望将这些数据存储并保存在我的计算机上。现在我在本地运行XAMPP。

当我输入表单标签时,它会重定向。我想保存数据。

假设用户(我自己)在“johnmayer@gmail.com”的电子邮件中添加“John Mayer”之类的名称,在点击sumbit按钮后如何在PHP页面上保存该信息?

3 个答案:

答案 0 :(得分:0)

包含HTML表单的数据输入页面应如下所示:

<form action="save-data.php" method="POST">
    <input name="firstname" type="text" />
    <input name="lastname" type="text" />
    <input type="submit" name="submit" value="Save Data">
</form>

现在位于名为save-data.php的PHP文件中:

<?php
if(isset($_POST['firstname']) && isset($_POST['lastname'])) {
    $data = $_POST['firstname'] . '-' . $_POST['lastname'] . "\n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}

请注意&#39; tmp / mydata.txt&#39;是要写入数据的文件的路径。它必须具有正确的写权限。

答案 1 :(得分:0)

HTML:

<form action="mailer.php?savedata=1" method="post">
    First Name: <input type="text" name="first_name"><br>
    LastName: <input type="text" name="last_name"><br>
    Your Email: <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>

PHP:

<?php
    $savedata = $_REQUEST['savedata'];
    if ($savedata == 1){ 
       $data = $_POST['first_name'];
       $data .= $_POST['last_name'];
       $data .= $_POST['email'];
       $file = "YOURDATAFILE.txt"; 

       $fp = fopen($file, "a") or die("Couldn't open $file for writing!");
       fwrite($fp, $data) or die("Couldn't write values to file!"); 

       fclose($fp); 
       echo "Your Form has been Submitted!";

   }
?>

答案 2 :(得分:0)

非常感谢你们。我自己编写了一些代码后想出了这个。

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>HTML</title>
        <meta name="author" content="nelly" />
        <!-- Date: 2016-01-01 -->
    </head>
    <body>
<?php

echo 'Hello' . htmlspecialchars($_POST["first_name"]);

    $input = $_POST["first_name"];
    $handle = fopen("savingData.txt" , "a+");
    $fileName = 'savingData.txt';
    $data = $handle;
    if (is_writable($fileName))
    {
        if (!$handle = fopen($fileName, 'a+'))
        {
            echo "Cannot open file ($fileName)";
            exit; 
        }

        if (fwrite($handle, $input ) === FALSE)
        {
            echo "Cannot write to file name";
            exit;
        }

        echo "Success wrote ($input) to file ($fileName)";

        fclose($handle);
    }

    echo "the file name is not writable?"


?>
    </body>
</html>