PHAO THU
PHAO THU

Reputation: 135

How can I connect to mongodb replica sets and authenticate by php script?

I use following php script to connect to mongodb replica set:

$conn = new MongoClient("mongodb://mongodb1:27017,mongodb2:27017/?replicaSet=MyRepSet");

$db = $conn->test;
$collection = $db->items;

$item = array(
    'name' => 'milk',
    'quantity' => 10,
    'price' => 2.50,
    'note' => 'skimmed and extra tasty'
  );

  $collection->insert($item);

 $conn->close();

This works when I start mongodb without --auth and --key

However, when I start mongodb replica set with --auth and --key, and create a user, like this:

> use test;
> db.addUser("test","123456")

When I try again with the above php script, I get this error:

Uncaught exception 'MongoCursorException' with message 'mongodb3:27017: not authorized for insert on test.items

How can I connect to mongodb replica set and authenticate by php script?

Upvotes: 3

Views: 5162

Answers (2)

PHAO THU
PHAO THU

Reputation: 135

Base on your hint I try following:

on both mongodb1 and mongodb2:

use admin;
db.addUser("admin","123456");

Edit the php connection script:

$conn = new MongoClient("mongodb://admin:123456@mongodb1:27017,mongodb2:27017/?replicaSet=MyRepSet");

It worked !!!! Thanks a lots

Upvotes: 0

SSpoke
SSpoke

Reputation: 5836

try this

$connection = new Mongo("mongodb://test:[email protected]:27017/mongodb1/?replicaSet=MyRepSet");

or if that doesn't work this try

$conn = new MongoClient("mongodb://test:123456@mongodb1:27017,mongodb2:27017/?replicaSet=MyRepSet");

Upvotes: 3

Related Questions