【发布时间】:2026-02-15 20:40:01
【问题描述】:
我正在尝试使用 HTML 和 PHP 制作联系表格。表单的 PHP 如下:
<?php
if(isset($_POST['email'])) {
// Email to information
$email_to ="personalemail@email.com";
$email_subject ="Contact";
$email_from ="Person";
// Error code
function died($error) {
echo "We are sorry, but there were error(s) found with the form you submitted.";
echo "These errors appear below.<br/><br/>";
echo $error. "<br/><br/>";
echo "Please go back and fix these errors.<br/>";
die();
}
// Validation
if(!isset($_POST['fname']) || !isset($_POST['lname']) || !isset($_POST['email']) || !isset($_POST['message'])) {
died('We are sorry but there appears to be a problem with the form you submitted.');
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$message = $_POST['message'];
$error_message = "";
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_message .= 'The email address you entered does not appear to be valid.<br/>';
}
$string_exp = "/^[A-Za-z.'-]+$/";
if(!preg_match($string_exp, $fname)) {
$error_message .= 'The first name you entered does not appear to be valid.<br/>';
}
if(!preg_match($string_exp, $lname)) {
$error_message .= 'The last name you entered does not appear to be valid.<br/>';
}
if(strlen($message) < 2) {
$error_message .= 'The message you entered does not appear to be valid.<br/>';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
$email_message .= "Name:" . clean_string($fname) . clean_string($lname) . "\n";
$email_message .= "Email:" . clean_string($email) . "\n";
$email_message .= "Message:" . clean_string($message) . "\n";
// Create email headers
$headers = 'From: ' .$email_From . "\r\n". 'Reply-To:' . $email. "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
?>
Thankyou for contacting me. I will be in contact with you shortly. <br/>
Please click <a href="index.html">here</a> to go back to the main website
<?php
}
?>
问题是提交表单时,它从不向我自己的个人电子邮件发送电子邮件。我还需要在虚拟主机上设置什么,还是纯粹是代码中的问题?我对要放入的适当代码进行了一些研究,并尝试了许多不同的选项,但似乎都没有奏效。
【问题讨论】:
-
你在本地主机上试试这个吗?
-
您遇到什么错误?您是否尝试打印错误?
-
我在测试之前将它上传到服务器,这样 PHP 才能真正工作。我没有收到任何错误,我只是从未收到来自表单的电子邮件。
-
你检查你的垃圾文件夹了吗?
标签: php html css forms contact