PHP 邮件表单安全性:发现新行的最可靠方法


php mail form security: most reliable way to spot new lines

我正在尝试建立一个安全的php联系表单,以允许用户(希望不是垃圾邮件发送者)发送邮件。

我正在研究在 from: 字段中检测新行的方法,用户将使用该字段提交他们的电子邮件地址和主题:字段。

我有 2 种具有相同功能的替代方案来检测新行,我希望您对哪一个最可靠(意味着在大多数情况下有效)发表意见:

function containingnewlines1($stringtotest) {
    if (preg_match("/(%0A|%0D|''n+|''r+)/i", $stringtotest) != 0) {
        echo "Newline found. Suspected injection attempt";
        exit;
    }
}
function containingnewlines2($stringtotest) {
    if (preg_match("/^'R$/", $stringtotest) != 0) {
        echo "Newline found. Suspected injection attempt";
        exit;
    }
}

提前感谢您的意见!

干杯

更相关的问题是"哪一个更可靠? 这两种方法的效率都无关紧要,因为这两种方法的执行时间都不应超过几毫秒。 试图根据毫秒在两者之间做出决定是一种微优化。

此外,效率是什么意思? 你的意思是哪个更快? 哪一个消耗的内存最少? 效率是一个定义不明确的术语,您需要更具体。

如果您绝对必须根据性能/效率要求做出决定,那么我建议您构建一个基准并自己找出最符合您要求的基准,因为归根结底只有您可以回答这个问题。

我又给自己添加了 2 个函数,并对100000循环进行了基准测试:

function containingnewlines3($stringtotest) {
   return (strpbrk($stringtotest,"'r'n") !== FALSE);
}
function containingnewlines4($stringtotest) {
   return (strpos($stringtotest,"'n") !== FALSE && strpos($stringtotest,"'r'n") !== FALSE);
}
$start = microtime(TRUE);
for($x=0;$x<100000;$x++) {
   containingnewlines1($html);   // 0.272623 ms
   containingnewlines2($html);   // 0.244299 ms
   containingnewlines3($html);   // 0.377767 ms
   containingnewlines4($html);   // 0.142282 ms
}
echo (microtime(TRUE) - $start);

实际上,我决定使用第一个函数,因为它涵盖了另外 2 种情况(%OA 和 %OD),并且它还包括不同操作系统('、'''r 等)使用的所有新行字符变体。