如何使我的HTML代码和php联系表单文件有效?

时间:2014-02-10 17:22:38

标签: php html

我在使用contact.php表单时遇到问题。在我根本没有收到我的电子邮件的消息之前,电子邮件确实已经发送了,这就是它所显示的:

From:  
E-mail:  
Message:

这是我的html表单:

<form role="form" class="form-alt" action="contact.php" method="post">
            <div class="form-group">
                <label for="name" class="sr-only">name</label>
                <input type="text" class="form-control" id="name" placeholder="Name (Required)">
            </div>
            <div class="form-group">
                <label for="email" class="sr-only">Email</label>
                <input type="email" class="form-control" id="email" placeholder="Email (Required)">
            </div>
            <div class="form-group">
                <label for="subject" class="sr-only">Subject</label>
                <input type="text" class="form-control" id="subject" placeholder="Subject">
            </div>
            <div class="form-group">
                <label for="message" class="sr-only">message</label>
                <textarea id="message" class="form-control" cols="30" rows="7" placeholder="Message"></textarea>
            </div>
            <button type="submit" class="btn btn-default">Enviar</button>
        </form>

        </div>

这是PHP联系人文件:

<?php
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_message = $_POST['cf_message'];

$mail_to = 'mail@example.com';
$subject = 'Message from a site visitor '.$field_name;

$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;

$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) { ?>
    <script language="javascript" type="text/javascript">
        alert('Thank you for the message. We will contact you shortly.');
        window.location = 'contact_page.html';
    </script>
<?php
}
else { ?>
    <script language="javascript" type="text/javascript">
        alert('Message failed. Please, send an email to gordon@template-help.com');
        window.location = 'contact_page.html';
    </script>
<?php
}
?>

1 个答案:

答案 0 :(得分:4)

您需要为每个表单元素指定一个名称属性。例如:

<input type="email" class="form-control" id="email" placeholder="Email (Required)">

应该是:

<input type="email" name="cf_email" class="form-control" id="email" placeholder="Email (Required)">

您的代码,例如$field_email = $_POST['cf_email'];正在寻找名为cf_email的输入元素。如果没有它,你会得到一个空白值。