我在丢弃的网站上有一个非常基本的表单,工作正常(姓名,电子邮件,消息)。
最近,我开始接收大量垃圾邮件,其中名称字段通过一些随机的字母和数字组合,电子邮件通过一些随机电子邮件地址和消息字段为空白。我认为这是一个学习更好的现场验证的好机会。
我首先使用HTML5输入模式属性实现客户端解决方案。这很有效,除了你所期望的,spambot只是绕过客户端验证。
我用于邮件功能的预装PHP使用针对注入的功能。由于我不了解很多PHP,我试图模拟该函数结构,以便验证名称字段只包含字母和空格(一旦我使用它,我会回去添加几个额外的字符)
它现在无法正常工作。我很确定问题在于我如何在顶部编写变量。我已经尝试在我的nameCleaned函数中切换if / true,else / false以确保我没有向后获取逻辑。无论字段中是否有数字,该函数都会发送邮件,或者在正确输入输入时将错误消息杀死它...取决于我的方式。
PHP
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$fromName = $_POST['fromName'];
$fromEmail = $_POST['fromEmail'];
$customerMessage = $_POST['customerMessage'];
//Validate first
if(empty($fromName)||empty($fromEmail))
{
echo "We at least need your name an email";
exit;
}
if(nameCleaned($fromName))
{
echo "Stop spamming me please";
exit;
}
if(IsInjected($fromEmail))
{
echo "That doesn't look like a valid email address";
exit;
}
if(nameCleaned($fromName))
{
echo "Quit spamming us";
exit;
}
$email_from = 'ourdomain.com Web Message';//<== Email From
$email_subject = "Message from ourdomain.com";//<== Email Subject
//Begin Email Body
$email_body = "$fromName is emailed us through the website. \n\n".
"EMAIL ADDRESS: \n$fromEmail \n\n".
"HERE'S WHAT THEY SAID: \n$customerMessage \n\n".
$to = "ouremail@domain.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $fromEmail \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//Mail sent, redirect
header('Location: http://ourdomain.com/thank-you.html');
// nameCleaned function
function nameCleaned($str){
if(preg_match("/^[a-zA-Z0-9\_]{2,35}/"))
{
return false;
}
else
{
return true;
}
}
// 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 false;
}
else
{
return true;
}
}
表格
<form method="post" action="assets/php/mailForm-validate.php">
<div class="field half first"><input type="text" name="fromName" placeholder="Name" /></div>
<div class="field half"><input type="email" name="fromEmail" placeholder="Email" /></div>
<div class="field"><textarea name="customerMessage" placeholder="Message" rows="6"></textarea></div>
<ul class="actions">
<li><input type="submit" name="submit" value="Send Message" /></li>
</ul>
</form>
答案 0 :(得分:0)
问题出在您的nameCleaned
功能中。
您正在使用preg_match()
函数,但只提供了一个参数。
preg_match
至少需要2个参数。第一个是模式,第二个是主题。您的主题是$str
变量。所以这是正确的代码:
preg_match("/^[a-zA-Z0-9\_]{2,35}/", $str)
这是完整的功能:
function nameCleaned($str){
if(preg_match("/^[a-zA-Z0-9\_]{2,35}/", $str))
{
return false;
}
else
{
return true;
}
}
我希望,我帮忙!