我有一个表单,在提交时使用内置的php mail()
函数发送电子邮件。
我如何:
或
我更喜欢选项1。
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "ok. (Here pop up saying its submitted and redirects)"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
答案 0 :(得分:1)
当您提交表单时,您启动一个新请求,以便PHP可以输出您喜欢的任何html / javascript;您也可以告诉它重定向到新页面。
因此,您可以轻松实现任一选项,以显示弹出窗口,您只需输出相关的javascript。
如果您的意思是弹出一个简单的警告对话框,那么您需要输出的javascript是alert('Email sent successfully')
- 如果您打算打开一个新窗口,那么它将是window.open('newpage.html')
无论哪种方式,您都需要将命令包装在脚本标记中:
echo "<script>alert('Email sent successfully');</script>";
这应放在<head>
或<body>
标记中。
当您说重定向时,我不确定是否有必要,但这取决于您放置代码的位置。发送电子邮件后,您可以选择输出完全不同的HTML,从而制作新页面。您需要确保您的电子邮件代码在旧页面的任何输出之前发生。 e.g。
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//process form and send email
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) {
include 'emailsent.php';
}else{
$include 'emailerror.php';
}
}else{
include 'form.php'
}
你可以用一系列回声取代包含或突破php
if ($mail) {
?><html>...</html><?php
}
如果您真的想要重定向,可以使用标头功能发送Location标头:
header('Location: emailsent.html');
请在此处查看php文档:http://php.net/manual/en/function.header.php
如果你这样做,你必须确保在任何输出开始之前(回声/打印等)这样做 - 这也包括你的PHP之前的任何内容,例如<html><?php
会导致这样的错误:
警告:无法修改标头信息 - 第23行/some/file.php中已经发送的标头(/some/file.php:12开始输出)
您可以在此处找到有关此内容的更多信息:How to fix "Headers already sent" error in PHP
答案 1 :(得分:0)