Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check validation mongodb id with php

i get mongodb id of query string. how to check validation this id? i want if mongodb id not valid redirect to another url

get query string:

    if(count($_GET)>0 && $_GET['uid']){

            //get id from string query
            $query = array("_id" => new MongoId($_GET

['uid']));
        $user = DB::findone('users',$query);

    }else{
        //redirect if not exist query string
        header('location:'.ADMIN_URL.'/items/forbidden.php');
    }  

plz help... thanks


2 Answers

In new PHP Mongo library https://github.com/mongodb/mongo-php-library the best way to check validity of a string is: (thanks to Yii2 code https://github.com/yiisoft/yii2-mongodb/tree/master/src/validators)

   function isValid($value)
    {
        if ($value instanceof \MongoDB\BSON\ObjectID) {
            return true;
        }
        try {
            new \MongoDB\BSON\ObjectID($value);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
like image 134
hpaknia Avatar answered Oct 23 '25 06:10

hpaknia


Since ext-mongo version 1.5 you can check it

if(isset($_GET['uid']) && MongoId::isValid ($_GET['uid'])) { 
 // Your code here 
}

php.net mongoid.isvalid

like image 22
Alexander Serkin Avatar answered Oct 23 '25 06:10

Alexander Serkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!