PHP and MongoDB Web Development Beginner s Guide

by Rubayeet Islam

PHP and MongoDB Web Development Beginner s Guide Combine the power of PHP and MongoDB to build dynamic web 2 0 applications

Publisher :

Author : Rubayeet Islam

ISBN : 9781849513623

Year : 2011

Language: en

File Size : 6.19 MB

Category : Computers Technology



PHP and MongoDB
Web Development
Beginner's Guide

Combine the power of PHP and MongoDB to build
dynamic web 2.0 applications

Rubayeet Islam

BIRMINGHAM - MUMBAI



PHP and MongoDB Web Development
Beginner's Guide

Copyright © 2011 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly
or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies
and products mentioned in this book by the appropriate use of capitals. However, Packt
Publishing cannot guarantee the accuracy of this information.

First published: November 2011

Production Reference: 1181111

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84951-362-3
www.packtpub.com

Cover Image by Charwak A ([email protected])



Credits
Author
Rubayeet Islam
Reviewers
Sam Millman

Copy Editor
Laxmi Subramanian
Project Coordinator
Kushal Bhardwaj

Sigert de Vries
Nurul Ferdous
Vidyasagar N V
Acquisition Editor
Usha Iyer
Development Editor
Susmita Panda
Technical Editors
Joyslita D'Souza
Veronica Fernandes
Lubna Shaikh

Proofreader
Matthew Humphries
Indexer
Tejal Daruwale
Graphics
Valentina D'silva
Production Coordinator
Prachali Bhiwandkar
Cover Work
Prachali Bhiwandkar



About the Author
Rubayeet Islam is a Software Developer with over 4 years of experience in large-scale
web application development on open source technology stacks (LAMP, Python/Django,
Ruby on Rails). He is currently involved in developing cloud-based distributed software that
use MongoDB as their analytics and metadata backend. He has also spoken in seminars
to promote the use of MongoDB and NoSQL databases in general. He graduated from the
University of Dhaka with a B.S. in Computer Science and Engineering.
I thank the Almighty for giving me such a blessed life and my parents for
letting me follow my passion. My friend and colleague, Nurul Ferdous, for
inspiring me to be an author in the first place. Finally, the amazing people
at Packt – Usha Iyer, Kushal Bhardwaj, Priya Mukherji, and Susmita Panda,
without your help and guidance this book would not have been possible
to write.



About the Reviewers
Sam Millman, after achieving a B.Sc. in Computing from the University of Plymouth,
immediately moved to advance his knowledge within Web development, specifically PHP. He
is a fully self-taught professional Web Developer and IT Administrator working for a company
in the south of England.
He first started to show an interest in MongoDB when he went in search of something
new to learn. Now he is an active user of the MongoDB Google User Group and is about to
release a new site written in PHP with MongoDB as the primary data store.

Sigert de Vries (1983) is a professional Web Developer working in The Netherlands. He has
worked in several companies as a System Administrator and Web Developer. He is a specialist
in high performance websites and is an open source enthusiast. With his communicative
skills, he translates advanced technical issues to "normal" human language.
Sigert is currently working at Worldticketshop.com, helping them to be one of the largest
ticket marketplaces in Europe. Within the company, there's plenty of room to use NoSQL
solutions such as MongoDB.
I would like to thank Packt publishing for asking me to review this book, it
has been a pleasure!



Vidyasagar N V was interested in Computer Science since an early age. Some of his serious
work in computers and computer networks began during his high school days. Later, he went
to the prestigious Institute Of Technology, Banaras Hindu University for his B.Tech. He has
been working as a Software Developer and Data Expert, developing and building scalable
systems. He has worked with a variety of 2nd, 3rd, and 4th generation languages. He has
worked with flat files, indexed files, hierarchical databases, network databases, relational
databases, NoSQL databases, Hadoop, and related technologies. Currently, he is working
as a Senior Developer at Ziva Software Pvt. Ltd., developing big database-structured dataextraction techniques for the Web and local information. He enjoys producing high-quality
software, web-based solutions, and designing secure and scalable data systems.
I would like to thank my parents, Mr. N Srinivasa Rao and Mrs.Latha Rao,
and my family who supported and backed me throughout my life. My
friends for being friends, and all those people willing to donate their time,
effort, and expertise by participating in open source software projects.
Thank you Packt Publishing for selecting me as one of the technical
reviewers on this wonderful book. It is my honor to be a part of this book.
You can contact me at [email protected]



www.PacktPub.com
Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to
your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for
a range of free newsletters and receive exclusive discounts and offers on Packt books and
eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print and bookmark content
• On demand and accessible via web browser

Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials for
immediate access.





Table of Contents
Preface
Chapter 1: Getting Started with MongoDB
The NoSQL movement
Types of NoSQL databases
MongoDB – A document-based NoSQL database
Why MongoDB?
Who is using MongoDB?
MongoDB concepts—Databases, collections, and documents
Anatomy of document
BSON—The data exchange format for MongoDB
Similarity with relational databases

Downloading, installing, and running MongoDB
System requirements
Time for action – downloading and running MongoDB on Windows
Installing the 64-bit version
Time for action – downloading and running MongoDB on Linux
Installing MongoDB on OS X
Configuring MongoDB
Command-line parameters
File-based configuration

1
7
8
8
9
9
9
10
10
11
11

12
12
13
14
15
17
17
17
18

Stopping MongoDB

18

Hitting Control + C
From the mongo shell
Sending INT or TERM signal in UNIX

Creating databases, collections, and documents
Time for Action – creating databases, collections, and documents
Installing the PHP driver for MongoDB
Time for Action – installing PHP driver for MongoDB on Windows
Installing the PHP-MongoDB driver on Unix



18
19
19

19
19
21
21
23

Table of Contents

Connecting to the MongoDB server from PHP
Creating a PHP-Mongo connection
Time for action – creating a connection to the MongoDB server from PHP
Configuring the PHP-MongoDB connection
Specifying timeout for the connection attempt
Summary

Chapter 2: Building your First MongoDB Powered Web App
A MongoDB powered blog
Have the MongoDB server running
Inserting documents in MongoDB
Time for action – building the Blog Post Creator
Creating databases and collections implicitly
Performing 'safe' inserts
Benefits of safe inserts

23
23
24
26
26
27

29
30
30
30
30
35
35
36

Specifying a timeout on insert
Setting the user generated _id
The MongoDate object
Querying documents in a collection
Time for action – retrieving articles from a database
The Mongo Query Language
The MongoCursor object
Conditional Queries

36
37
37
38
38
42
42
44

Doing advanced queries in MongoDB
Time for action – building the Blog Dashboard
Returning a subset of fields
Sorting the query results
Using count, skip, and limit
Performing range queries on dates
Updating documents in MongoDB
Time for action – building the Blog Editor
Optional arguments to the update method
Performing 'upsert'
Using update versus using save
Using modifier operations
Setting with $set
Incrementing with $inc
Deleting fields with $unset
Renaming fields with $rename

45
45
49
49
49
50
51
51
55
55
56
56
56
57
57
57

Deleting documents in MongoDB
Time for action – deleting blog posts
Optional arguments to remove

58
58
63
[ ii ]



Table of Contents

Managing relationships between documents
Embedded documents
Referenced documents
Time for action – posting comments to blog posts
Embedded versus referenced – Which one to use?
Querying embedded objects

63
64
64
64
69
69

Summary

71

Chapter 3: Building a Session Manager
Understanding HTTP sessions
Understanding PHP native session handling
Time for action – testing native PHP session handling
Limitations of native PHP session handling
Implementing session handling with MongoDB
Extending session handling with session_set_save_handler
The SessionManager class
Time for action – building the SessionManager class
How the SessionManager works
The constructor
The open and close methods
The read method
The write method
The destroy method
The gc method

73
74
74
74
78
78
78
79
79
83
83
84
84
84
84
85

Putting the SessionManager in action
Time for action – putting SessionManager into action
Building the user authentication module
Time for action – building the User class
Creating the login, logout, and user profile page
Time for action – creating the login, logout, and profile page
Using good session practices
Setting low expiry times of session cookies
Using session timeouts
Setting proper domains for session cookies
Checking for browser consistency
Summary

Chapter 4: Aggregation Queries

85
86
88
89
92
93
99
99
100
100
100
101

103

Generating sample data
Time for action – generating sample data
Understanding MapReduce
Visualizing MapReduce
Performing MapReduce in MongoDB
[ iii ]



104
104
107
108
109

Table of Contents

Time for action – counting the number of articles for each author
Defining the Map function
Defining the Reduce function
Applying the Map and Reduce
Viewing the results
Performing MapReduce on a subset of the collection
Concurrency
Performing MongoDB MapReduce within PHP
Time for action – creating a tag cloud
Performing aggregation using group()
Time for action – calculating the average rating per author
Grouping by custom keys
MapReduce versus group()
Listing distinct values for a field
Time for action – listing distinct categories of articles
Using distinct() in mongo shell
Counting documents with count()
Summary

Chapter 5: Web Analytics using MongoDB
Why MongoDB is a good choice as a web analytics backend
Logging with MongoDB
Time for action – logging page visits with MongoDB
Capped collections
Sorting in natural order
Updating and deleting documents in a capped collection
Specifying the size of a regular collection
Convert a regular collection to a capped one

Extracting analytics data with MapReduce
Time for action – finding total views and average response time per blog post
The map, reduce, and finalize functions
Displaying the result
Running MapReduce in real time versus running it in the background

110
111
112
112
113
114
114
114
115
120
121
124
124
125
125
127
127
128

129
130
131
131
134
135
135
135
136

136
137
140
140
141

Real-time analytics using MongoDB
Time for action – building a real-time page visit counter
Summary

141
141
146

Chapter 6: Using MongoDB with Relational Databases

147

The motivation behind using MongoDB and an RDBMS together
Potential use cases
Defining the relational model
Time for action – creating the database in MySQL
[ iv ]



148
148
149
150

Table of Contents

Caching aggregation results in MongoDB
Time for action – storing the daily sales history of products in MongoDB
Benefits of caching queries in MongoDB
Storing results of expensive JOINs
Using MongoDB for data archiving
Time for action – archiving old sales records in MongoDB
Challenges in archiving and migration
Dealing with foreign key constraints
Preserving data types

153
153
160
160
160
161
163
163
163

Storing metadata in MongoDB
Time for action – using MongoDB to store customer metadata
Problems with using MongoDB and RDBMS together
Summary

164
164
173
173

Chapter 7: Handling Large Files with GridFS

175

What is GridFS?
The rationale of GridFS
The specification
Advantages over the filesystem
Storing files in GridFS
Time for action – uploading images to GridFS
Looking under the hood
Serving files from GridFS
Time for action – serving images from GridFS
Updating metdata of a file
Deleting files
Reading files in chunks
Time for action – reading images in chunks
When should you not use GridFS
Summary

175
176
176
177
178
178
181
182
183
186
186
187
187
189
190

Chapter 8: Building Location-aware Web Applications with
MongoDB and PHP
A geolocation primer
Methods to determine location
Detecting the location of a web page visitor
The W3C Geolocation API
Browsers that support geolocation

191
192
192
193
193
194

Time for action – detecting location with W3C API
The Geolocation object
The getCurrentPosition() method

194
198
198

Drawing the map using the Google Maps API
[v]



199

Table of Contents

Geospatial indexing
Time for action – creating geospatial indexes
Geospatial indexing – Important things to know
Performing location queries
Time for action – finding restaurants near your location
The geoNear() command
Bounded queries
Geospatial haystack indexing
Time for action – finding nearby restaurants that serve burgers
Summary

Chapter 9: Improving Security and Performance
Enhancing query performance using indexes
Time for action – creating an index on a MongoDB collection
The _id index
Unique indexes
Compound keys indexes
Indexing embedded document fields
Indexing array fields
Deleting indexes
When indexing cannot be used
Indexing guidelines
Choose the keys wisely
Keep an eye on the index size
Avoid using low-selectivity single key indexes
Be aware of indexing costs
On a live database, run indexing in the background

Optimizing queries
Explaining queries using explain()

200
201
202
203
203
208
210
210
211
215

217
217
218
221
221
222
223
224
224
224
225
225
225
225
226
226

227
227

Optimization rules

228

Using hint()
Profiling queries

228
229

Understanding the output
Optimization rules

229
230

Securing MongoDB
Time for action – adding user authentication in MongoDB
Creating an admin user
Creating regular user
Viewing, changing, and deleting user accounts
User authentication through PHP driver
Filtering user input
Running MongoDB server in a secure environment
[ vi ]



230
230
232
233
233
234
235
235

© 2018-2019 uberlabel.com. All rights reserved