preg_match 用于防止 PHP 形式的注入

发布于 2024-12-20 17:34:36 字数 1010 浏览 0 评论 0原文

我是 PHP 的绝对初学者,尝试设置验证以停止联系表单上的标头注入。我已经阅读了很多教程,并制作了一个应该验证的表单,但它不起作用...在这里研究了一些之后,我的问题似乎是我使用的代码使用了 eregi (旧教程),它应该是 preg_match这些日子。我已经使用 preg_match 来验证电子邮件地址格式,但我想确保没有换行符、抄送、密件抄送等可以隐藏在任何地方。 这是我现在拥有的功能:

    function spamcheck($field) {
if(eregi("to:",$field) || eregi("cc:",$field) || eregi("Content-Type:",$field) || eregi("bcc:",$field) || eregi("%0D",$field) || eregi("\r",$field) || eregi("\n",$field) || eregi("%0A",$field)){ 
    $possiblespam = TRUE;
}else $possiblespam = FALSE;
if ($possiblespam) {
    die("Possible spam attempt detected. If this is not the case, please edit the content of the contact form and try again.");
    return 1;
}

}

现在,我不确定是否可以像这样用 preg_match 替换 eregi :

     if(preg_match("/to:/i",$field) 
     // and so on for each string I want to catch

我在这里读到 preg_match 需要分隔符,不确定我是否正确使用了它们。另外,应该区分大小写,所以我添加了 i 标志(没有信心)。尽管如此,仍然不知道上述内容是否真的正确。这看起来安全吗?再次为我缺乏 PHP 知识而道歉。这种函数在网上教程中很常见,但使用的是eregi而不是preg_match。

I am an absolute beginner with PHP, trying to set up a validation to stop header injection on a contact form. I've read a lot of tutorials, and made a form that should validate, but it's not working... after researching a little here it seems my problem is that the code I have uses eregi (old tutorial), which should be preg_match these days. I have used preg_match to validate the email address format, but I want to make sure no line breaks, cc, bcc etc can be snuck in anywhere.
This is the function I have now:

    function spamcheck($field) {
if(eregi("to:",$field) || eregi("cc:",$field) || eregi("Content-Type:",$field) || eregi("bcc:",$field) || eregi("%0D",$field) || eregi("\r",$field) || eregi("\n",$field) || eregi("%0A",$field)){ 
    $possiblespam = TRUE;
}else $possiblespam = FALSE;
if ($possiblespam) {
    die("Possible spam attempt detected. If this is not the case, please edit the content of the contact form and try again.");
    return 1;
}

}

Now, I'm not sure if I could just replace eregi with preg_match like so:

     if(preg_match("/to:/i",$field) 
     // and so on for each string I want to catch

I have read here that preg_match needs delimiters, not sure if I've used them right. Also, should be case sensitive, so I added the i flag (without confidence). Still, no real idea if above would actually be correct. Does that seem secure? Again, apologies for my lack of PHP knowledge. This kind of function is quite common in online tutorials, but using eregi rather than preg_match.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

习ぎ惯性依靠 2024-12-27 17:34:36

只需检查换行符就足够了:

$possiblespam = (0 !== preg_match("~(\r|\n)~", $field));

Just checking for line breaks should be enough:

$possiblespam = (0 !== preg_match("~(\r|\n)~", $field));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文