so using the mongodb shell, I was able to create a database and add a username and password to it. How can I do the same in php? I have everything installed and able to connect to mongodb server.
However, I can't find any information in the doc.
so using the mongodb shell, I was able to create a database and add a username and password to it. How can I do the same in php? I have everything installed and able to connect to mongodb server.
However, I can't find any information in the doc.
I do not believe addUser() is implemented in the PHP driver.
However, there is an execute that should allow you to do an addUser() the same way you would from the mongo shell:
EDIT: After testing, I couldn't get execute to do what you wanted, but I did find that the following works:
<?php
// open connection
$mongo = new Mongo("mongodb://" . MONGO_USER . ":" . MONGO_PASS . "@" . MONGO_HOST, array("persist" => "abcd1234"));
$db = $mongo->selectDB("admin");
// user info to add
$username = "testUser";
$password = "testPassword";
// insert the user - note that the password gets hashed as 'username:mongo:password'
// set readOnly to true if user should not have insert/delete privs
$collection = $db->selectCollection("system.users");
$collection->insert(array('user' => $username, 'pwd' => md5($username . ":mongo:" . $password), 'readOnly' => false));
?>
That adds a new user to the admin db on my server - checked via mongo shell after executing PHP script.
That said - why do you want to add a Mongo user from a PHP script?
The MongoDB distribution includes bin/mongo, the MongoDB interactive shell. This utility is a JavaScript shell that allows you to issue commands to MongoDB from the command line. So, if execute allows you to pass arbitrary Javascript to the Mongo engine, then you should be able to use the same addUser command you used in the shell. I'll test it on one of my Mongo installs shortly and report back.execute although it's probably some mistake I'm making. However, after digging around, I did find something that should work - see my edit above$db = $mongo->selectDB("usersDatabaseNameGoesHere") instead. I haven't done it, but that's what the docs say: mongodb.org/display/DOCS/…A way to create a new mongodb user from PHP is via MongoDB::command:
//info to add
$db_name = 'db_name';
$db_user = 'new_user';
$db_pass = 'new_pass';
//autenticate with a user who can create other users
$mongo = new MongoClient("mongodb://root:root@localhost/admin");
$db = $mongo->selectDB( $db_name );
//command to create a new user
$command = array
(
"createUser" => $db_user,
"pwd" => $db_pass,
"roles" => array
(
array("role" => "readWrite", "db" => $db_name)
)
);
//call MongoDB::command to create user in 'db_name' database
$db->command( $command );
Tested with mongo 3.0 and PHP mongo driver 1.6