Home > Uncategorized > First Application using MongoDB & PHP

First Application using MongoDB & PHP

I have been eyeing on MongoDB since I had visited IIIT Hyderabad for campus placements in Jan 2011.  The name MongoDB was introduced to me by the candidates whom I had to interview.  Infact all the candidates who took the interview had worked on MongoDB for solving some problem during their graduate studies.   MongoDB, the name comes from HuMongous DataBase, which is a well instituted name and the database indeed is meant for storing tonnes of data organized in JSON format.   Being a C++ coder, I had less experience with JSON and have always avoided that as it was primarily used in the Web application development.  After learning about Mongo in the official wiki, I got thrilled by the simplicity of JSON format and the advantage of it over the conventional XML format and infact decided to use JSON for a project that my team is working on.
MongoDB is written in C++, which increased my love towards the database.  I wanted to use MongoDB for my product development data store needs, but was stuck with the dependencies of Mongo’s C++ driver, where it wanted Boost libraries to be linked.  The pathetic problem is boost does not compile with the debug version of STLport.  My product is built on STLport, so I have to link MongoDB with Boost/STLport, which works well in release mode, but not in DEBUG mode.  How Sad!
My desperation grew as I wanted to have some useful application developed using MongoDB.  PHP came for my rescue. The PHP driver that was available with MongoDB is a cute baby.   I works like moon walk, when copy pasted on the PHP’s extension folder.   The documentation of PHP/MongoDB is well written and has lot of examples.  Also, there is awesome support available in the internet for all the doubts that I got while building my Brower based Photo SlideShow web application.  All, I did was, I pushed all my JPEG files into MongoDB and wrote simple PHP scripts to fetch the files based on the file name.  When the file name was not mentioned, my script would pick a file randomly.  I have presented the code below:
# view.php

# get the file id
$id = "";
if ( array_key_exists( "id", $_REQUEST ) ) {
    $id = $_REQUEST["id"];
}

# open database connectivity
$conn = new Mongo();
$store = $conn->store;
$image = $store->image;

# fetch the file as per the id or just randomly
if ( $id != "" ) {
    $query = array ( 'id' => $id );
    $cursor = $image->find( $query );
}
else {
    # set the html headers for refreshing the page every 3 sec.
    header( 'Refresh: 3;' );

    # Random fetch logic, get the count first.
    $count = $image->find()->count();
    $rand = rand( 1, $count-1 );  # generate a random number.
    # skip several records of the cursor based on the random number
    $cursor = $image->find()->skip( $rand )->limit(1);  
}

# write output stream as JPEG content
header( 'Content-Type: image/jpeg' );
foreach ( $cursor as $obj ) {
    # decode the data, and just write on the output stream.
    echo base64_decode($obj["data"]);
}

# import.php

$dir = $_REQUEST["dir"];
if ( $dir == "" ) {
    echo "<h2>Import directory cannot be empty</h2>";
    exit;
}

$conn = new Mongo();
$db = $conn->store;
$image = $db->image;

echo "<ol>";
$dhandle = opendir( $dir );
while ( ($file = readdir( $dhandle )) != false ) {
    $path = $dir."/".$file;
    if ( is_dir( $path ) ) {
        continue;
    }

    $path = str_replace( '\\', '/', $path );
    $handle = fopen( $path, "rb" );
    $data = fread( $handle, filesize( $path ) );
    fclose( $handle );
    if ( $data == false ) {
	continue;
    }

    $key = preg_replace( "/[[:punct:]]/", "_", $file );
    echo "<li>Importing $path (Key: $key)...";
    try {
        $image->insert( array( "id" => $key, 
               "data" => base64_encode( $data ) ), true );
        echo "Success";
    }
    catch ( MongoCursorException $e ) {
        echo "Exception: $e";
    }
	
    echo "</li>";
    ob_flush();
}

echo "</ol>";

Within minutes, I was able to have a browser based slide show application, which protected all my image files in the Database without being exposed out in the folder system.

I am enjoying every bit of Mongo, and hope to develop several application using that in the future.

Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.