Book Image

PHP and MongoDB Web Development Beginner's Guide

Book Image

PHP and MongoDB Web Development Beginner's Guide

Overview of this book

With the rise of Web 2.0, the need for a highly scalable database, capable of storing diverse user-generated content is increasing. MongoDB, an open-source, non-relational database has stepped up to meet this demand and is being used in some of the most popular websites in the world. MongoDB is one of the NoSQL databases which is gaining popularity for developing PHP Web 2.0 applications.PHP and MongoDB Web Development Beginner’s Guide is a fast-paced, hands-on guide to get started with web application development using PHP and MongoDB. The book follows a “Code first, explain later” approach, using practical examples in PHP to demonstrate unique features of MongoDB. It does not overwhelm you with information (or starve you of it), but gives you enough to get a solid practical grasp on the concepts.The book starts by introducing the underlying concepts of MongoDB. Each chapter contains practical examples in PHP that teache specific features of the database.The book teaches you to build a blogging application, handle user sessions and authentication, and perform aggregation with MapReduce. You will learn unique MongoDB features and solve interesting problems like real-time analytics, location-aware web apps etc. You will be guided to use MongoDB alongside MySQL to build a diverse data back-end. With its concise coverage of concepts and numerous practical examples, PHP and MongoDB Web Development Beginner’s Guide is the right choice for the PHP developer to get started with learning MongoDB.
Table of Contents (17 chapters)
PHP and MongoDB Web Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface

Time for action - reading images in chunks


We are going to make some changes in our earlier example. When serving an image file from GridFS to the browser, we are going to read the image in chunks, instead of loading the entire file in memory. Let's see how we can do that:

  1. 1. Create a new PHP file in your text editor and add the following lines of code to it:

    <?php
    $id = $_GET['id'];
    require 'dbconnection.php';
    $mongo = DBConnection::instantiate();
    $gridFS = $mongo->database->getGridFS();
    $object = $gridFS->findOne(array('_id' => new MongoId($id)));
    //find the chunks for this file
    $chunks = $mongo->database->fs->chunks->find(array('files_id'
    => $object->file['_id']))
    ->sort(array('n' => 1));
    header('Content-type: '.$object->file['filetype']);
    //output the data in chunks
    foreach($chunks as $chunk){
    echo $chunk['data']->bin;
    }
    
  2. 2. Save the file as stream.php.

  3. 3. Open the list.php file. Find the following line in it:

    <a href="image.php?id=<?php...