preg_match用户名验证正则表达式允许>和<尽管这些字符没有被列入白名单 [英] preg_match username validation regex allows > and < despite those characters not being whitelisted
问题描述
我有一个相对简单的用户名正则表达式
I have this relatively simple regex for usernames
// Enforce that username has to be 3-100 characters, alphanumeric, and first character a letter.
// Possibility without begin/end characters and i: [a-z][a-z0-9@.+-_]{2,100}
// Allow for simple email usernames in the future...
return !!preg_match('#^[a-zA-Z][a-zA-Z0-9@.+-_]{2,100}$#', trim($username));
不幸的是,其中允许使用这些支持XSS的测试字符串:
Which, unfortunately, allows these XSS-ready test strings:
'angle<bracket',
'angle>bracket',
'html<script>inside',
我不知道为什么,因为正则表达式已明确禁止使用它们.
And I have no idea why since they already should explicitly be disallowed by the regex.
这是一个正在运行的测试用例:
Here is a running test case:
任何人都知道为什么不明确允许使用正则表达式的尖括号?我是否应该将其中的一个字符(.+-)换成文字?
Anyone know why angle brackets are being allowed by a regex that doesn't explicitly allow for them? Am I supposed to escape one of those characters (.+-) as literals?
推荐答案
我认为是因为:[+-_]
您要包含"+"和"_"之间的所有字符,请尝试将顺序更改为[+_-]
(在末尾加上破折号),或者转义破折号.
You are including all chars between '+' and '_', try changing the order to [+_-]
(putting the dash at the end) or escape the dash.
这篇关于preg_match用户名验证正则表达式允许>和<尽管这些字符没有被列入白名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!