jamcoupe
jamcoupe

Reputation: 1452

case insensitive find in mongodb for usernames in php

I am trying to find a way to query mongodb in a case insensitive way using PHP because currently when checking a user "Username" and "username" can both be diffrent usernames...

$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!";
}

I tried this but the cursor only looks for a case sensitive match so it will only lowercase the cursor value if it has one.

Upvotes: 3

Views: 7042

Answers (2)

John Linhart
John Linhart

Reputation: 1816

Since MongoRegex has been deprecated, use MongoDB\BSON\Regex. Updated example from previous answer:

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

I wrapped the POST variable in preg_quote() to sanitise possibly harmful characters.

Upvotes: 10

Aurélien B
Aurélien B

Reputation: 4640

PHP Mongo driver has an internal Regex Object:

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

And btw I strongly recommand to check $_POST value and probably transform you regex to get only username (without more before/after => new MongoRegex('/^' . $securevalue . '$/i')

Edit: my answer wasn't precise: starting anchor allow mongo to use index on this query, if available.

Upvotes: 13

Related Questions