防止在php中拦截一些字符\ r,\ n,%0A,%0D的邮件注入

问题描述 投票:2回答:2

我想在php中使用用于邮件注入的特殊字符阻止人们发送垃圾邮件。例如,\n\r用于连接几个标题,因此也与%0A%0D连接。所以我写了一个正则表达式来匹配它们。但是我怀疑我的正则表达式效率不高......有些东西让我觉得我写的东西无法使用......任何帮助都表示赞赏,谢谢。

这是我想做的一个基本例子......

if (!preg_match('/^[^\s]./', $_POST['name']) || (preg_match('/(%0A|%0D|\\n+|\\r+|;|mime-version:|content-type:|content-transfer-encoding:|subject:|to:|cc:|bcc:)/i', $_POST['name'])) || !(strpos($_POST['name'],'\r') === false) || !(strpos($_POST['name'],'\n') === false)) {
  exit("Warning: your Name contains illegal characters! This mail will not be sent!");
} elseif (!preg_match('/^[^\s]./', $_POST['subject']) || (preg_match('/(%0A|%0D|\\n+|\\r+|;|mime-version:|content-type:|content-transfer-encoding:|subject:|to:|cc:|bcc:)/i', $_POST['subject'])) || !(strpos($_POST['subject'],'\r') === false) || !(strpos($_POST['subject'],'\n') === false)) {
  exit("Warning: your Subject contains illegal characters! This mail will not be sent!");
} elseif (!preg_match('/^[a-zA-Z0-9]+([_\\.-][a-zA-Z0-9]+)*'.'@([a-zA-Z0-9]+([\.-][a-zA-Z0-9]+))+$/', $_POST['mail'])) {
  exit("Warning: your Mail contains no valid email address! This mail will not be sent!");
} elseif (!preg_match('/^[^\s]./', $_POST['message'])) {
  exit("Warning: your Message connot be empty! This mail will not be sent!");
} else {
  $name = $_POST['name'];
  $mail = $_POST['mail'];
  $subject = $_POST['subject'];
  $message = $_POST['message'];
  mail($to, $subject, $message, $headers, "-f$mail") {
  exit("Your Mail is sent! Thanks!");
}

为了匹配\n\r%0A%0D我应该如何写我的正则表达式?

!(strpos($_POST['subject'],'\r') === false) !(strpos($_POST['subject'],'\n') === false)

很好吗?

谢谢。

php regex email code-injection spam
2个回答
2
投票

我做了一个测试。测试结果很成功!我用不同的方法直接在localhost测试了正则表达式:

<?php
$test = "the dog \n was \r sleeping on the floor";
if (preg_match_all('/(%0A|%0D|\\n+|\\r+|;|mime-version:|content-type:|content-transfer-encoding:|subject:|to:|cc:|bcc:)/i', $test, $tmp)) {
  echo "I found this character: '";
  print_r($tmp[1]);
  echo "'";
} else {
  echo "I cannot find any string searched";
}
?>

结果:

I found this character: 'Array ( [0] => [1] => ) '

看源,我可以看到\ n和\ r

I found this character: 'Array
(
    [0] => 

    [1] => 
)
'

所以我认为正则表达式很好。

我用strpos()做的其他测试:

if !(strpos($_POST['subject'],'\n') === false)) {

单引号失败,同时找到带双引号的\ n ...

if !(strpos($_POST['subject'],"\n") === false)) {

结论:正则表达式形成良好,strpos()需要“”匹配\ n或\ r。


0
投票

我对正则表达式不是很透彻,但我可以通过为您的问题提供替代技巧解决方案来帮助您。

您可以使用以下代码来解决您的目的。

<?php

function sanitize_strings($raw_string) {
    return preg_replace("/[^0-9a-zA-Z_\-\\\%]+/", "", $raw_string);
}

if( $raw_string == sanitize_strings($raw_string) )
{
    echo "No illegal characters found.";
}
else
{
    echo "Illegal characters found.";
}

?>

希望这对你有用。 :)

© www.soinside.com 2019 - 2024. All rights reserved.