<?php
// configure
$from = 'Demo contact form <demo@domain.com>';
$sendTo = '105 Questions <myemail@example.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from the website\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
这是我对某些代码以}
结尾而感到困惑的地方,我得到了错误。
但是,当我添加?>
时,它可以正常运行,但也会在页面加载时发送电子邮件。
在我读过的另一篇文章中,他们用isset
修复了它,但当我把它放在&#34;配置评论&#34;之前仍然在页面加载时发送了一封电子邮件。
答案 0 :(得分:0)
基本逻辑 - 除非您正在处理表单提交而不是页面加载,否则不要发送消息。
if (isset($_POST['name'])) { //This will not be true on a page load
//Your existing script goes here
}