我的php电子邮件表单没有返回用户输入的数据

时间:2016-03-31 13:35:56

标签: php forms email

正如标题中所述,虽然正在返回字段标签,但我的webform并未在电子邮件中返回用户信息。

我认为这是一个问题,HTML的结构与PHP字段名称无关,但我不知道如何格式化。

有人能让我走上正轨吗?

这是HTML:

<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
              <div class="row-fluid">
                <div class="span5">
                    <label>First Name</label>
                    <input type="text" class="input-block-level" required="required" placeholder="Your First Name">
                    <label>Last Name</label>
                    <input type="text" class="input-block-level" required="required" placeholder="Your Last Name">
                    <label>Email Address</label>
                    <input type="text" class="input-block-level" required="required" placeholder="Your email address">
                </div>
                <div class="span7">
                    <label>Message</label>
                    <textarea name="message" id="message" required class="input-block-level" rows="8"></textarea>
                </div>

            </div>
            <button type="submit" class="btn btn-primary btn-large pull-right">Send Message</button>

        </form>

这是php:

<?php
header('Content-type: application/json');
$status = array(
    'type'=>'success',
    'message'=>'Email sent!'
);

$name = @trim(stripslashes($_POST['name'])); 
$email = @trim(stripslashes($_POST['email'])); 
$subject = @trim(stripslashes($_POST['subject'])); 
$message = @trim(stripslashes($_POST['message'])); 

$email_from = $email;
$email_to = 'Example@email.com';

$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;

$success = @mail($email_to, $subject, $body, 'From: <'.$email_from.'>');

echo json_encode($status);
die;

2 个答案:

答案 0 :(得分:0)

您需要为输入提供name属性,例如:

<input type="text" name="name" class="input-block-level" required="required" placeholder="Your First Name" />

然后,您就可以像现在一样访问$_POST数据。查看name attribute docs

答案 1 :(得分:0)

首先,您的输入没有name属性:

<input type="text" class="input-block-level" required="required" name="first_name" placeholder="Your First Name">

<input type="text" class="input-block-level" required="required" name="last_name" placeholder="Your Last Name">

<input type="text" class="input-block-level" required="required" name="email" placeholder="Your email address">

其次,您需要使用<input>代替<button>。否则,您的表单将不会被提交。

<input type="submit" class="btn btn-primary btn-large pull-right">Send Message</input>

第三,您需要使用isset()函数检查表单是否已提交:

// will return true if the form is submitted
if(isset($_POST['submit']){
    header('Content-type: application/json');
    // other parts of your code
}

最后,您不应该通过删除@来抑制错误消息,因为它们对于帮助您调试错误非常有用,尤其是当您遇到语法错误时。