PHP - 在没有错误时提交错误信息
问题描述:
因此,我已经构建了此电子邮件表单,如果未提交名称或/和电子邮件,应该显示错误消息'名称和电子邮件是必需的'。但是,如果他们是我收到相同的消息。这怎么解决?PHP - 在没有错误时提交错误信息
<?php
if(!isset($_POST['submit-enquiry']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$guest_email = $_POST['email'];
$mobile = $_POST['mobile'];
$message = $_POST['enquiry-message'];
//Validate first
if(empty($name)||empty($guest_email))
{
echo '<script language="javascript">';
echo 'alert("Name and email are mandatory")';
echo '</script>';
exit;
}
if(IsInjected($visitor_email))
{
echo '<script language="javascript">';
echo 'alert("Bad Email Value")';
echo '</script>';
exit;
}
$email_from = $guest_email;//<== update the email address
$email_subject = "Enquiry from $name";
$email_body = "Name: $name. \n". "Mobile: $mobile .\n". "Message: $message. \n";
$to = "my_email";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $guest_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: enquiry.php');
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
的fprm的HTML:
<div id="enquiry-form">
<form method="post" name="enquiry-form" action="" target="_self">
<span class="short-input" id="name">
<h6>name</h6>
<input type="text" name="name">
</span>
<span class="short-input" id="mobile">
<h6>mobile</h6>
<input type="text" name="mobile">
</span>
<span class="long-input" id="email">
<h6>e-mail</h6>
<input type="text" name="email">
</span>
<span class="long-input" id="enquiry-message">
<h6>enquiry</h6>
<textarea name="enquiry-message"></textarea>
</span>
</div>
<div id="contact-info">
<h2>Contact Details</h2>
</div>
<button type="submit" id="submit-enquiry" name="submit-enquiry">send</button>
</form>
答
尝试
if($name=='' || $guest_email=='')
在某些情况下空洞会导致意想不到的结果。我的经验让我说,对于表单验证,最好通过这种方式检查变量是否为空。然后你检查变量的内容(例如,看看它是否是一个有效的电子邮件),所以这对我来说足够安全。 如果你的代码仍然不起作用,那么有必要做进一步的调查。
+0
这不提供问题的答案。要批评或要求作者澄清,请在其帖子下方留言。 –
+0
你是对的。当我在电话中时,我错误地发布了我的答案,并且缺少部分文本。 :) –
答
if(empty(trim($name)) || empty(trim($guest_email)))
你能做一个$ _POST转储吗? 你确定你的表单没有使用GET而不是POST吗? 也许向我们展示表单的HTML? – Spode