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

jam*_*upe 2 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!";
}
Run Code Online (Sandbox Code Playgroud)

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

Alp*_*haB 13

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

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

顺便说一句,我强烈建议检查$ _POST值,并可能转换你的正则表达式只获得用户名(没有更多的前/后=> new MongoRegex('/^' . $securevalue . '$/i')

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


Joh*_*art 10

由于MongoRegex已被弃用,请使用MongoDB\BSON\Regex。更新了之前答案的示例:

$cursor = $collection->findOne(
    [
        'username' => new \MongoDB\BSON\Regex(preg_quote($_POST['value']), 'i')
    ]
);
Run Code Online (Sandbox Code Playgroud)

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