我正在使用strpos函数来验证用户提交的url,我想确保我没有遗漏任何允许用户绕过验证并提交不合适的url的内容。
以下面的例子为例,如果我只希望用户能够输入与youtube域相关的url,我不希望他们能够在其中放入通配符(*)或其他会"欺骗"strpos函数的东西。
$url = $request->input('url');
// Check if Youtube url is found
if (strpos($url, 'http://youtube.com') > -1)
{
// some code
}
// some code
谢谢!
strpos
在未找到条件下返回false,如果字符串出现在第一列中则返回0
,这在PHP中也类似于false
,因此使用===
或!==
会更准确
$url = $request->input('url');
// Check if Youtube url is found
if (strpos($url, 'http://youtube.com') !== FALSE)
{
// some code when youtube is found in url
}
最好使用正则表达式。
^(https?':'/'/)?(www'.)?(youtube'.com|youtu'.?be)'/.+$
试试看。
请记住使用类型安全方程进行测试。
strpos
将查找字符串中第一个出现的位置。所以如果字符串(位置0)的开头有匹配
if (strpos($url, 'http://youtube.com') > -1)
将返回0,该0将被解释为CCD_。你在这里遇到麻烦了。
相反,要安全地打字:
if (strpos($url, 'http://youtube.com') !== false)
这意味着,无论在字符串的哪个位置找到子字符串,它都将被认为是真的,并且您知道存在匹配。