Sunday, December 22, 2013

MongoDB: Getting Started With CRUD Operations

MongoDB is No-Sql Open Source database system which uses document as record of database.
MongoDB is designed for high performance and high accessibility.  

Document is set of field => value pair combination and store this information in form of BSON ( BSON is binary representation of JSON records) which is native data type in most of languages.

MongoDB store set of documents in the form of collection.

Now let’s see the basic operations which can be handled in MongoDB.
  •          Create
  •          Read
  •          Update
  •         Delete

Collectively called CRUD operation

Create Operation

MongoDB perform atomic create operation on single document. It adds new document to selected collection.

                 field => value,
                 field => value,
                 field => value,

Here value could be simple datatype or complex (document or array)
Create operation always add unique identifier of ObjectId data type to newly created document.

ObjectId is 12 byte BSON primarily used to maintain uniqueness in collection. Following is byte structure of ObjectId.

  • 4 byte for Unix epoch value
  • 3 byte for machine identifier
  • 2 byte for process identifier
  • 3 byte for some random value


                name : “Zainul”,
                address : "XYZ Address"

Read Operation

Read operation fetches documents from single or selected collection. It uses projection and condition to modify resulting documents.

  •     Project is used to fetch only select fields of document which help to increase read operation.
  •     Condition is used to select particular document which falls under given condition.

           { condition },
           { projection }

We can use limit and sort to limit and order resulting documents

Note:  order of resulting documents is not defined unless we provide order for documents


        { name: ‘Zainul’ },
        { name : 1, email : 1}

This command will return set of documents from user collection whose name matches with given condition and fetch only name and email.

Note: read operation always returns id unless we omit it by using query projection

Update Operation

Update operation modify existing document or even create new document. It uses update criteria to isolate documents and update action to modify values of selected documents.

           { update criteria },
           { update action },
           { update option }

Update option tells MongoDBto update multiple documents.


        { name : 'Zainul' },
        { $set : { name :  "Abedin' } }

Note:  use upsert to create a new document if that document does not exist.

Delete Operation

Delete operation remove single or multiple documents from selected collection. It uses remove criteria to identify the document which is to be removed.

     {remove criteria}

If remove criteria is not defined then it will remove all the documents.



      { name :  'Abedin' }

These basic operation will help to get started with MongoDB CRUD operation.

Thursday, December 5, 2013

How To Watermark A Photo Using PHP

Hello Friends, This blog post will help you to create a watermark image using PHP. But first let’s get introduce yourself with watermarking.

What is Watermark?
Watermark is a marker which is embedded inside image (other media). It is use to identify the ownership.

Why we need Watermarking?
Watermarking helps to maintain integrity and avoid unauthorized use for images (other media source also).

For example let’s suppose you are have image hosting website and you provide unique and beautiful images to user. If you want only authorize user should download your images then you need to provide image preview with watermarking and original image to authorized user only so that unauthorized user cannot misuse it.

Now let look at some coding stuff.

First example shows watermarking images with text, normally we use copyright text.
And second example show watermarking with watermark image.

Watermarking using text

// set water mark text
$watermark = 'watermark';

//create source image
$source_image = imagecreatefromjpeg('images/some_image.jpg');

//get image width & height position
$image_x = imagesx($source_image);
$image_y = imagesy($source_image);

$font_size = 48;  //font size

//set font for watermark text
// you can use any font 
// source
$font = 'Roboto-Light.ttf';

// create font size for watermark text
$font_size_box = imagettfbbox($font_size, 0, $font, $watermark);

// generate water text position (middle)
$image_x = ($image_x / 2) - ($font_size_box[2] / 2);
$image_y = ($image_y / 2) - ($font_size_box[5] / 2);;

//create color (white color)
$image_color = imagecolorallocate($source_image, 250, 250, 250);

// create image from combination of image + text
imagettftext($source_image, $font_size, 0, $image_x, $image_y, $image_color, $font, $watermark);

// generate water mark image
imagejpeg($source_image, 'images/watermark_image.jpg');

Watermarking using image

// watermark image
$water_mark_image = imagecreatefrompng('images/watermark.png');

// image to be watermarked
$org_image = imagecreatefromjpeg('images/some_image.jpg');

$margin = 10;

// create watermark position inside original image
// bottom right corner
$water_mark_position_x = imagesx($org_image) - imagesx($water_mark_image) - $margin;
$water_mark_position_y = imagesy($org_image) - imagesy($water_mark_image) - $margin;

// center position
//$water_mark_position_x = imagesx($org_image) / 2 - imagesx($water_mark_image) / 2;
//$water_mark_position_y = imagesy($org_image) / 2 - imagesy($water_mark_image) / 2;

// create image copy by combining original image + watermark image
imagecopy($org_image, $water_mark_image, $water_mark_position_x, $water_mark_position_y, 0, 0, imagesx($water_mark_image), imagesy($water_mark_image));

// create watermark image from image copy
imagepng($org_image, 'images/waterking_image.png');

//destroy images source

If you are providing watermark image for download purpose then it is recommended to add watermark at center position and if it is for only preview then you can add it top corner or bottom corner

Wednesday, November 27, 2013

JavaScript : Flash Title For New Message

Whenever you chat with your friends on Facebook or Gmail, you often see new blinking message which appears on Title of browser when you’re on other webpage or tab.

I always feel how they would notify us with this message. After some research I found that it is a small JavaScript which makes this happen.

This tutorial post will help you to flash Title of web browser for new message.

Let’s look at some JavaScript stuff

    var message_interval = null;
    var user = 'Zainul';
    var message = 'Hello There';
    var odd_even = 0;
    var old_title = document.title;

     * Show title message when new message arrives 
    function showTitleMessage() {
        // set time interval
        message_interval = setInterval(function() {
            // reset title and execute next task when user returs to this tab
            $(window).bind('focus', function() {
                document.title = old_title;
                // execute next task
                // use callback function for next task

            //set message
            document.title = odd_even ? message : user + ' says...';
            // set odd or even
            odd_even = !odd_even;

        }, 2000);

You can use this tutorial to show new message arrives when you are looking at message list, example Stack overflow questions, Chat message.

Hope this tutorial will help you.

Monday, November 25, 2013

CSS: How To Create Custom Scrollbar For Webkit Supported Browsers

One of eye catching thing of Gmail new updates was its scrollbar. First I thought it would be an html element represented by some kind of Javascript. But after some time I realized that it was not Javascript effect rather it is a CSS effects for scrollbars.

One amazing thing about this scrollbars are, they can be represented in different style for different HTML elements within same webpage.

Today we will see the implementation of such scrollbar for Webkit supported browsers.

First we will look at basic CSS properties of scrollbar.


Following image shows location these properties within scrollbar.

Now let’s look at the one basic example

                min-height: 1000px;
                width: 10px;
                background: #fff;
                -webkit-box-shadow: inset 1px 1px 2px rgba(0,0,0,0.1);

                background: #aaa;
                box-shadow: 0px 0px 1px rgba(0,0,0,0.5);
                background: #888;
                background: #444;

You can also customize scrollbars of overflow HTML elements, like this
<div id="custom-scrollbar">
            <div class="content">
                <!-- some HTML stuff -->

And CSS code

#custom-scrollbar {
                width: 20%;
                height: 300px;
                overflow: auto;
                background: #eee;
                height: 600px;
                width: 10px;
                background: #fff;
                -webkit-box-shadow: inset 1px 1px 2px rgba(0,0,0,0.1);
                border-radius: 10px;
                background: #F77;
                box-shadow: 0px 0px 1px rgba(0,0,0,0.5);
                border-radius: 10px;
                background: #A55;
                background: #744;
Hope you would like this post.

Wednesday, November 20, 2013

Preload Images Using Javascript

Preload Image is technique which helps browser to render images with minimum delay.

preload images

Today we will see example of image gallery. Gallery contain 5 images which load images one after another whenever user clicks next and back button.

This is a basic image gallery scenario which is used in all possible website, then why we need preloaded images for this gallery?

Now a day’s most of website becoming faster and user expectation is increasing.

Suppose your website doesn’t use preload image technique for gallery and a user visits any image gallery from Google Plus or Facebook and visits your website gallery.

Then that user always prefer those websites rather than yours. Why?

Because your website load one image at a time. When user click on next button, then only gallery load image and user has wait till it get loaded.

To avoid this situation gallery needs to download all images first so that browser cached them and when user clicks next button image get fetched from browser cache rather than image server.

Now let look at some programming related stuff

// first we create JSON record of images
var imageRecord = ['image1.jpg',

// now iterate each JSON record to load image
for (var pos = 0; pos < imageRecord.length; pos++) {

    // create image object
    var image = new Image();

    // assign image path
    image.src = imageRecord[pos];

    // additional stuff
    // some time we need to perform some logic after image load
    // it is hard to remember which image is loaded in a loop 
    // therefore we assign attribute to image which identifies JSON record of that image
    image.setAttribute('img-pos', pos);
    // bind load event to image
    Image.onload = function() {

        // get image position

        // perform operation based on fetch image index
Browser downloads images (other static resource) parallel per hostname. Therefore we can’t predict which image get downloaded first. That is why we added the image position attribute to identify which image is loaded.

If you have only few images then you can use following code

<img src = “image 1” width=”1” height=”1” />
<img src = “image 2” width=”1” height=”1” />
<img src = “image 3” width=”1” height=”1” />

As it occupy only small part of browser and all images get downloaded and cached.

Hope this tutorial post will help you.

Friday, November 8, 2013

How To Implement Review Rich Snippet

Rich snippet helps to create more interactive appearance of your webpage in SERP.

There are different sets of Rich snippet which are approved by Google.

Today we will see the how to implement Review – Rich snippet. provides vocabulary to create snippet that SERP page shows result with additional information like ratings, review count, description.

Let’s implement this snippet.

Here is sample example without snippet.

Basho’s is one of the best restaurant in Pune - by Zainul, October 1, 2013
4/5 stars
Very nice ambiance, food & service. ...!

Now we will add vocabulary for this page.

<div itemprop="review" itemscope itemtype="">    <span itemprop="name">Basho’s is one of the best restaurant in Pune </span> -    by<span itemprop="author">Zainul</span>,
    <div itemprop="reviewRating" itemscope itemtype="">
      <meta itemprop="worstRating"content="1">
      <span itemprop="ratingValue">4</span>/
      <span itemprop="bestRating">5</span>stars
    <meta itemprop="datePublished" content="2013-10-01">October 1, 2013
    <span itemprop="description”>Very nice ambiance, food & service. ...!</span>

If required snippet information is not present in HTML then you can use meta tag to add snippet information. Like in above example we used meta tags for worstRating and datePublished.

Now validate you webpage in Rich snippet tools.

After all this process SERP won’t show your page with rich snippet.  What?
It will, but you need to wait till Google fetch this page, index it and validate rich snippet after that it will come in SERP.

Rich snippet does not increase page rank, rather your webpage standout in SERP by rich content.

Saturday, October 26, 2013

Twitter: How To Implement Summary Card

Hello Friends, this tutorial will help you to implement one of the Twitter card, Summary Card.

There are different cards available in Twitter. like

  • Summary
  • Photo
  • Product
  • Gallery
  • App
  • Player

Today we will see implementation of Summary Card.

Summary card gives preview of website to reader which get shared via twitter.
It is a rich snippet which display Title, Description and Image of shared website. 

To use summary card you need to add few meta tags in your webpage.

Follow the given step to get these meta tags

2.   Choose Twitter Card, which is Summary.

3.   Add meta information 

twitter:site (Site Twitter Username)
twitter:title (Site/Webpage Title)
twitter:description (Site/Webpage Description)
twitter:creator (Site Twitter Creator)
twitter:image:src (Site/Webpage Image)
twitter:domain (Site Domain) 

4.   Then select sample embed code and put it into head section of your site/webpage.


5.    After updating meta tags into your website visit validation section of Twitter Card and click on “Validate & Apply” button.

6.     It will ask for website URL , then past your website URL where you have recently updated summary card.

7.    Put that URL and click “Go!”

8.    If all goes well then it will show Summary card preview of right side.

9.    If something goes wrong then it will gives you warning.

Hope this tutorial will help to get start with Twitter’s Summary card.

Thursday, October 24, 2013

jQuery: How To Make Your Image based Website Load Faster

Hello Friends, Today I am writing my second tutorial post regarding optimization of webpage which contains bulks of images.

Let’s consider one scenario where you want to display hundreds of images at a time. And also your client wants this webpage should load faster.

Now here is the problem, webpage won’t get loaded fully unless all of its images get download first. Which means as number of images in webpage increases the load time of that webpage also increased.

To solve this problem we must reduce the webpage load time, indirectly it means that we need to load less amount of images.

Consider a scenario where we load only one default image at each place of actual images indicating that these actual images are getting downloaded and using Javascript we will download these actual images after window finishes its loading.

Following diagrams will help you to understand the flow.

as one image wont takes too much time to load, therefore webpage speed increase and it also help to improve user experience as it tells user that all images are in the process of download.

Now we will see some code to implement this flow.
First create html page to store images.

 <img data-image="[actual-image-path]" src="default-loading-image-path" class="item"/>
  <img data-image="[actual-image-path]" src="default-loading-image-path"/ class="item">
  <img data-image="[actual-image-path]" src="default-loading-image-path"/ class="item">
  <img data-image="[actual-image-path]" src="default-loading-image-path"/ class="item">

here we have created four images,where we set default loading image in source property and actual image in image data property of image tag.

Now we will add jQuery script in head section to load all actual images after page get loaded.

 <script  type="text/javascript">
             //execute after window finishes loading
                   //search each image by its class name
                          //replace current image path with actual image path
 $(this).attr('src', $(this).data('image'));

script get executed after all component get downloaded and browser is ready to render them. at that time we load all images.

Hope it will help you.

Wednesday, October 16, 2013

AJAX - How To Retrieve JSON Response from PHP script

Hello Friends, This is my first tutorial post.

Today I'll explain you how to retrieve JSON response via Ajax call.

First we build a PHP script to send response in JSON format, then we will gather this response from an Ajax call through jQuery script.

Let’s first create a PHP script 

Create a PHP script, I’ll name it as “json_response.php”
And add following code in it



//set header for JSON response
header("Content-Type: application/json");

//render array in JSON format
echo json_encode(array('status' => 200, 'message' => 'Response from PHP script in JSON format.'));

This is a basic example to send JSON response.
PHP script will send response with status code and message.

Now create a HTML file to fetch JSON response and add it in header tag.

Create a HTML file, I’ll name it as “json_response.html”
And add following code.


                                                                                                                           <script src=""></script>                  
        <script type="text/javascript">                                                                                
            $('document').ready(function() {                                                                          
      //create ajax call to fetch json response                                                            
                $.ajax({                                                                                                                          url: 'json_header.php',                                                                                
                    type: 'GET',                                                                                               
                    dataType: 'JSON', // it is necessary to get JSON response                                                                                                         
                    success: function(response) {                                                                      
                       // if reponse status is success                                                                  
                        if (response.status == 200) {                                                            
       // add message to header tag                                                    
        <h1 id="message"></h1>                                                                             
Note: It is very important to add ajax request parameter  dataType: 'JSON' to fetch response in JSON format.

After running HTML file in browser you see the header tag has message as

Response from PHP script in JSON format.