Create Push Notifications Using Google Cloud Messaging PHP and MySQL in Android

Introduction

Google Cloud Messaging for Android (GCM): Helps the developer send data from servers and send data to our application. In other words when we send the request to the server then server returns a response to your application whenever new data is available instead of making a request to the server in a timely fashion.

Introduction to Google cloud messaging PHP and MySQL

This tutorial uses PHP as the server-side programming language and MySQL as the server-side database. The flow is provided by Android Google cloud Messaging.

Step 1

First an Android device sends its device id (sender id) to the GCM server for registration.

Step 2

When the registration is successfull the GCM Server returns a registration id to the Android device.

Step 3

After successfully receiving the registration id the device will send the registration id to our server.

Step 4

Store the registration id into the database.

Registering with Google Cloud Messaging.

Creating MySQL Database

  1. Open the phpmyadmin panel by going to http://localhost/phpmyadmin and create a database called GCM.

  2. Creating the database, select the database and execute the following query in the SQL tab to create the gcm_pushnotification_users table.
    1. CREATE TABLE IF NOT EXISTS `gcm_pushnotification_users ` (  
    2. `id` int(11) NOT NULL AUTO_INCREMENT,  
    3. `gcm_regid` text,  
    4. `namevarchar(50) NOT NULL,  
    5. `email` varchar(255) NOT NULL,  
    6. `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,  
    7. PRIMARY KEY (`id`)  
    8. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;  

Creating the PHP Project

Click on the xammp icon in the system tray then select PHP -> PHP Extensions -> Enable php_curl.

  1. Go to your xammp folder and inside the htdocs folder create a folder called gcm_server_php.

  2. Create a field called database_config.php. This field holds the database configuration and Google API key.

    database_config.php
    1. <?php  
    2.    /**  
    3.    * Database config variables  
    4.    */  
    5.    define("DB_HOST""localhost");  
    6.    define("DB_USER""root");  
    7.    define("DB_PASSWORD""");  
    8.    define("DB_DATABASE""pushnotification");  
    9.    /*  
    10.    * Google API Key  
    11.    */  
    12.    define("GOOGLE_API_KEY""BIzajiCRLa4LjkiuytloQBcRCYcIVYA45048i9i8zfClqc"); // Place your Google API Key  
    13. ?>  
  3. Create another file called database_connect.php. This file handles database connections and mainly opens and closes the connection.

    b_connect.php
    1. <?php  
    2.    class Database_Connect.{  
    3.    // Connecting to database  
    4.    public function connect() {  
    5.    require_once database_config.php ';  
    6.    // connecting to mysql  
    7.    $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);  
    8.    // selecting database  
    9.    mysql_select_db(DB_DATABASE);  
    10.    // return database handler  
    11.    return $con;  
    12.    }  
    13.       // Closing database connection  
    14.      public function close() {  
    15.       mysql_close();  
    16.    }  
    17. }  
    18. ?>  
  4. Create functions.php. This file contains the function to do database CRUD operations.

    functions.php
    1. <?php  
    2.    class Functions {  
    3.       private $db;  
    4.       //put your code here  
    5.       // constructor  
    6.       function __construct() {  
    7.          include_once './database_connect.php';  
    8.          // connecting to database  
    9.          $this->db = new Database_Connect();  
    10.          $this->db->connect();  
    11.       }  
    12.       // destructor  
    13.       function __destruct() {  
    14.       }  
    15.       /** 
    16.       * Storing new user 
    17.       * returns user details 
    18.       */  
    19.       public function storeUser($name$email$gcm_regid) {  
    20.          // insert user into database  
    21.          $result = mysql_query("INSERT INTO gcm_pushnotification_users (name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");  
    22.          // check for successful store  
    23.          if ($result) {  
    24.             // get user details  
    25.             $id = mysql_insert_id(); // last inserted id  
    26.             $result = mysql_query("SELECT * FROM gcm_pushnotification_users WHERE id = $id"or die(mysql_error());  
    27.             // return user details  
    28.             if (mysql_num_rows($result) > 0) {  
    29.                return mysql_fetch_array($result);  
    30.             } else {  
    31.                return false;  
    32.             }  
    33.             } else {  
    34.                return false;  
    35.             }  
    36.          }  
    37.          /** 
    38.          * Getting all users 
    39.          */  
    40.          public function getAllUsers() {  
    41.             $result = mysql_query("select * FROM gcm_pushnotification_users ");  
    42.             return $result;  
    43.          }  
    44.       }  
    45. ?>  
  5. Create GCM.php. This file sends push notification requests to the GCM server.

    GCM.php
    1. <?php    
    2.    class GCM {    
    3.       /**  
    4.       * Sending Push Notification  
    5.       */    
    6.       public function send_notification($registatoin_ids$message) {    
    7.          // include config    
    8.          include_once './database_connect.php';    
    9.          $url = 'https://android.googleapis.com/gcm/send';    
    10.          $fields = array(    
    11.          'registration_ids' => $registatoin_ids,    
    12.          'data' => $message,    
    13.          );    
    14.          $headers = array(    
    15.          'Authorization: key=' . GOOGLE_API_KEY,    
    16.          'Content-Type: application/json'    
    17.          );    
    18.          // Open connection    
    19.          $ch = curl_init();    
    20.          curl_setopt($ch, CURLOPT_URL, $url);    
    21.          curl_setopt($ch, CURLOPT_POST, true);    
    22.          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    
    23.          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
    24.          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    
    25.          curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));    
    26.          $result = curl_exec($ch);    
    27.          if ($result === FALSE) {    
    28.          die('Curl failed: ' . curl_error($ch));    
    29.       }    
    30.       // Close connection    
    31.       curl_close($ch);    
    32.       echo $result;    
    33.       }    
    34.    }    
    35. ?>   
  6. Create a register_user.php file. This file is used to receive requests from the Android device and stores the user in the database.

    register_user.php
    1. <?php  
    2.    $json = array();  
    3.    /** 
    4.    * Registering a user device 
    5.    * Store reg id in users table 
    6.    */  
    7.    if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"])) {  
    8.       $name = $_POST["name"];  
    9.       $email = $_POST["email"];  
    10.       $gcm_regid = $_POST["regId"]; // GCM Registration ID  
    11.       // Store user details in db  
    12.       include_once './functions.php';  
    13.       include_once './GCM.php';  
    14.       $db = new Functions();  
    15.       $gcm = new GCM();  
    16.       $res = $db->storeUser($name$email$gcm_regid);  
    17.       $registatoin_ids = array($gcm_regid);  
    18.       $message = array("product" => "shirt");  
    19.       $result = $gcm->send_notification($registatoin_ids$message);  
    20.       echo $result;  
    21.       } else {  
    22.          echo " user details missing";  
    23.    }  
    24. ?>  
  7. Create a send_pushnotification_message.php file. This file is used to send push notification to an Android device to send a request to the GCM server.

    send_pushnotification_message.php
    1. <?php  
    2.    if (isset($_GET["regId"]) && isset($_GET["message"])) {  
    3.       $regId = $_GET["regId"];  
    4.       $message = $_GET["message"];  
    5.       include_once './GCM.php';  
    6.       $gcm = new GCM();  
    7.       $registatoin_ids = array($regId);  
    8.       $message = array("price" => $message);  
    9.       $result = $gcm->send_notification($registatoin_ids$message);  
    10.       echo $result;  
    11.    }  
    12. ?>  
  8. Last and finally create a file called index.php and paste the following code into it. The following code will create a simple admin panel to list all the user devices and provides a panel to send push notification to individual devices.

    index.php
    1. <!DOCTYPE html>  
    2. <html>  
    3.    <head>  
    4.       <title></title>  
    5.       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    6.       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>  
    7.       <script type="text/javascript">  
    8.          $(document).ready(function(){  
    9.          });  
    10.          function sendPushNotification(id){  
    11.          var data = $('form#'+id).serialize();  
    12.          $('form#'+id).unbind('submit');  
    13.          $.ajax({  
    14.             url: "send_pushnotification_message.php",  
    15.             type: 'POST',  
    16.             data: data,  
    17.             success: function(data, textStatus, xhr) {  
    18.                $('.txt_message').val("");  
    19.             },  
    20.             error: function(xhr, textStatus, errorThrown) {  
    21.             }  
    22.          });  
    23.          return false;  
    24.       }  
    25.       </script>  
    26.    </head>  
    27. <body>  
    28. <?php  
    29.    include_once 'functions.php';  
    30.     $db = new Functions();  
    31.    $users = $db->getAllUsers();  
    32.    if ($users != false)  
    33.    $no_of_users = mysql_num_rows($users);  
    34.    else  
    35.       $no_of_users = 0;  
    36.    ?>  
    37.    <div class="container">  
    38.       <h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>  
    39.       <hr/>  
    40.      <ul class="devices">  
    41.       <?php  
    42.          if ($no_of_users > 0) {  
    43.       ?>  
    44.       <?php  
    45.          while ($row = mysql_fetch_array($users)) {  
    46.       ?>  
    47.       <li>  
    48.       <form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">  
    49.       <label>Name: </label> <span><?php echo $row["name"] ?></span>  
    50.       <div class="clear"></div>  
    51.       <label>Email:</label> <span><?php echo $row["email"] ?></span>  
    52.       <div class="clear"></div>  
    53.       <div class="send_container">  
    54.          <textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>  
    55.          <input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>  
    56.          <input type="submit" class="send_btn" value="Send" onclick=""/>  
    57.       </div>  
    58.    </form>  
    59.    </li>  
    60. <?php }  
    61. else { ?>  
    62.    <li>  
    63.       No Users Registered Yet!  
    64.    </li>  
    65.    <?php } ?>  
    66.    </ul>  
    67.    </div>  
    68. </body>  
    69. </html>