在mongodb中为php中的用户名发现不区分大小写

时间:2012-02-01 18:11:06

标签: php mongodb

我试图找到一种使用PHP以不区分大小写的方式查询mongodb的方法,因为目前在检查用户时“Username”和“username”都可以是不同的用户名......

$cursor = $collection->findOne(array('username' => /{$_POST['value']}/i));
$lowerInput = strtolower($_POST['value']);
$username = strtolower($cursor['username']);
if($lowerInput == $username){
    echo "That username appears to be in our database!";
}

我试过这个,但是光标只查找区分大小写的匹配,所以如果它有一个光标值,它只会小写。

2 个答案:

答案 0 :(得分:13)

PHP Mongo驱动程序有一个内部Regex对象:

$cursor = $collection->findOne(
  array('username' => new MongoRegex("/$_POST['value']/i")
);

顺便说一下,我强烈建议您检查$ _POST值,并可能将您的正则表达式转换为仅获取用户名(不包括更多/之后=> new MongoRegex('/^' . $securevalue . '$/i')

编辑:我的答案不准确:启动锚允许mongo在此查询上使用索引(如果可用)。

答案 1 :(得分:2)

由于不推荐使用MongoRegex,请使用MongoDB\BSON\Regex。上一个答案的更新示例:

'System.Collections.Generic.IEnumerable1[SimpleSurveyTest.Models.SurveyModel]'

我将POST变量包装在preg_quote()中以清理可能有害的字符。

相关问题