Connecting and authenticating to MongoDB database from PHP using MongoClient

December 23, 2012
By

In our previous article titled “Installing and configuring php mongo driver with Apache in Ubuntu 12.04 LTS“, we have seen, how to install and configure php-mongo driver to connect to a MongoDB database from php.

In this article, we will create a PHP program to connect to a MongoDB database by authenticating user name with password using MongoClient api.


1. Prerequisites for this PHP application

  • A web server with PHP and php-mongo driver installed
  • A MongoDB server with or with out authentication enabled

2. Create a file namely mongodemo.php in the document root of the web server with the given below php code


<?php

/**
    User name : admu
    Password : new_pass
    MongoDB host : localhost
    MongoDB port : 27017
    Database : university
*/

$server = "mongodb://admu:new_pass@localhost:27017/university";

/**
    Remove username and password, if you want
    to connect to an unauthenticated MongoDB database.
    See the example code below
*/
// $server = "mongodb://localhost:27017/university";

// Connecting to server
$c = new MongoClient( $server );

if($c->connected)
    echo "Connected successfully";
else
    echo "Connection failed";

?>


3. Code in Action

Open the php file namely “mongodemo.php” using its url in a web browser. If the connection to the MongoDB server is established successfully, then a page similar to the given below will be displayed.

Connecting to MongoDB server using MongoClient from PHP

Figure 1 : Connecting to MongoDB server using MongoClient from PHP


What is next?

An extension to this article is available at “A PHP program to insert individual and batch data into MongoDB database


 

How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , ,

One Response to Connecting and authenticating to MongoDB database from PHP using MongoClient

  1. André Gomes on August 19, 2013 at 7:45 pm

    Ty guy, this snippet help us on BR :)

Leave a Reply to André Gomes Cancel reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner