如何将数据从HTML / PHP表单保存到文本文件

时间:2016-11-19 10:21:43

标签: php html

我有一个表单,可以通过php文件向电子邮件发送信息。

我的HTML表单如下:

<form method="post" action="start-project.php">
<fieldset>
<span><input type="text" name="name" id="name" placeholder="Your Name" required/></span>
<span><input type="email" name="email" id="email" placeholder="Email Address" required/></span>
<span><input type="text" name="phone" id="phone" placeholder="Phone Number" required/></span>
<span><input type="text" name="website" id="website" placeholder="Website (Optional)" /></span>
</fieldset>
<span><input type="submit" name="submit" value="GET STARTED"></span>
</form>

我的php代码如下:

<?php

$EmailFrom = "email@domain.com";
$EmailTo = "receiver@email.com";
$Subject = "Submission: Start a Project";
$name = Trim(stripslashes($_POST['name'])); 
$phone = Trim(stripslashes($_POST['phone'])); 
$email = Trim(stripslashes($_POST['email'])); 
$website = Trim(stripslashes($_POST['website'])); 

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Website: ";
$Body .= $website;
$Body .= "\n";

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=sent.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>

如何将条目数据保存在服务器上的文本文件中? 我看过很少的文章,但我不知道如何用我的代码实现它。

我感谢任何帮助。

4 个答案:

答案 0 :(得分:3)

查看file_put_contents()

 $log = file_put_contents('logs.txt', $name.PHP_EOL , FILE_APPEND | LOCK_EX);

答案 1 :(得分:1)

如果对不存在的文件使用fopen(),则会创建它,

$file= "file.txt";
$fh = fopen($file, 'a') or die("can't open file");
$stringData = "new data 1\n";
fwrite($fh, $stringData);
$stringData = "New data 2\n";
fwrite($fh, $stringData);
fclose($fh);

答案 2 :(得分:0)

您可以将数据附加到文本文件中:

$myfile = fopen('files/file.txt', 'a');
fwrite($myfile, $data);
fclose($myfile);
  

php.net链接

答案 3 :(得分:0)

感谢所有帮助过的人。

我找到了这个解决方案,它对我很好。 如果有人遇到它,我会把它放在这里。

打开PHP标签后,我在PHP代码中添加了以下代码:

if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['website'])) {
    $data = $_POST['name'] . ' - ' . $_POST['email'] . ' - ' . $_POST['phone'] . ' - ' . $_POST['website'] . "\n";
    $ret = file_put_contents('file.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');
}