PHP 5.4.31 Released

Authentication

If MongoDB is started with the --auth or --keyFile options, you must authenticate before you can do any operations with the driver. You may authenticate a connection by specifying the username and password in either the connection URI or the "username" and "password" options for MongoClient::__construct().

Example #1 Authenticating against the "admin" database

<?php
// Specifying the username and password in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost");

// Specifying the username and password via the options array (alternative)
$m = new MongoClient("mongodb://localhost", array("username" => $username"password" => $password));
?>

By default, the driver will authenticate against the admin database. You may authenticate against a different database by specifying it in either the connection URI or the "db" option for MongoClient::__construct().

Example #2 Authenticating against normal databases

<?php
// Specifying the authentication database in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost/myDatabase");

// Specifying the authentication database via the options array (alternative)
$m = new MongoClient("mongodb://${username}:${password}@localhost", array("db" => "myDatabase"));
?>

If your connection is dropped, the driver will automatically attempt to reconnect and reauthenticate you.

add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top