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

Introduction

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

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

    b_connect.php

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

    functions.php

    1.    class Functions {  
    2.       private $db;  
    3.   
    4.   
    5.       function __construct() {  
    6.          include_once ‘./database_connect.php’;  
    7.   
    8.          $this->db = new Database_Connect();  
    9.          $this->db->connect();  
    10.       }  
    11.   
    12.       function __destruct() {  
    13.       }  
    14.  
    15.  
    16.  
    17.   
    18.       public function storeUser($name$email$gcm_regid) {  
    19.   
    20.          $result = mysql_query(“INSERT INTO gcm_pushnotification_users (name, email, gcm_regid, created_at) VALUES(‘$name’, ‘$email’, ‘$gcm_regid’, NOW())”);  
    21.   
    22.          if ($result) {  
    23.   
    24.             $id = mysql_insert_id();   
    25.             $result = mysql_query(“SELECT * FROM gcm_pushnotification_users WHERE id = $id”or die(mysql_error());  
    26.   
    27.             if (mysql_num_rows($result) > 0) {  
    28.                return mysql_fetch_array($result);  
    29.             } else {  
    30.                return false;  
    31.             }  
    32.             } else {  
    33.                return false;  
    34.             }  
    35.          }  
    36.  
    37.  
    38.   
    39.          public function getAllUsers() {  
    40.             $result = mysql_query(“select * FROM gcm_pushnotification_users “);  
    41.             return $result;  
    42.          }  
    43.       }  
    44. ?>  
  5. Create GCM.php. This file sends push notification requests to the GCM server.

    GCM.php

    1.    class GCM {    
    2.        
    3.  
    4.     
    5.       public function send_notification($registatoin_ids$message) {    
    6.            
    7.          include_once ‘./database_connect.php’;    
    8.          $url = ‘https://android.googleapis.com/gcm/send’;    
    9.          $fields = array(    
    10.          ‘registration_ids’ => $registatoin_ids,    
    11.          ‘data’ => $message,    
    12.          );    
    13.          $headers = array(    
    14.          ‘Authorization: key=’ . GOOGLE_API_KEY,    
    15.          ‘Content-Type: application/json’    
    16.          );    
    17.            
    18.          $ch = curl_init();    
    19.          curl_setopt($ch, CURLOPT_URL, $url);    
    20.          curl_setopt($ch, CURLOPT_POST, true);    
    21.          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    
    22.          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
    23.          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    
    24.          curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));    
    25.          $result = curl_exec($ch);    
    26.          if ($result === FALSE) {    
    27.          die(‘Curl failed: ‘ . curl_error($ch));    
    28.       }    
    29.         
    30.       curl_close($ch);    
    31.       echo $result;    
    32.       }    
    33.    }    
    34. ?>   
  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.    $json = array();  
    2.  
    3.  
    4.  
    5.   
    6.    if (isset($_POST[“name”]) && isset($_POST[“email”]) && isset($_POST[“regId”])) {  
    7.       $name = $_POST[“name”];  
    8.       $email = $_POST[“email”];  
    9.       $gcm_regid = $_POST[“regId”];   
    10.   
    11.       include_once ‘./functions.php’;  
    12.       include_once ‘./GCM.php’;  
    13.       $db = new Functions();  
    14.       $gcm = new GCM();  
    15.       $res = $db->storeUser($name$email$gcm_regid);  
    16.       $registatoin_ids = array($gcm_regid);  
    17.       $message = array(“product” => “shirt”);  
    18.       $result = $gcm->send_notification($registatoin_ids$message);  
    19.       echo $result;  
    20.       } else {  
    21.          echo ” user details missing”;  
    22.    }  
    23. ?>  
  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.    if (isset($_GET[“regId”]) && isset($_GET[“message”])) {  
    2.       $regId = $_GET[“regId”];  
    3.       $message = $_GET[“message”];  
    4.       include_once ‘./GCM.php’;  
    5.       $gcm = new GCM();  
    6.       $registatoin_ids = array($regId);  
    7.       $message = array(“price” => $message);  
    8.       $result = $gcm->send_notification($registatoin_ids$message);  
    9.       echo $result;  
    10.    }  
    11. ?>  
  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.   
    2.   
    3.      
    4.         
    5.       “Content-Type” content=“text/html; charset=UTF-8”>  
    6.         
    7.         
    8.      
    9.   
    10.    include_once ‘functions.php’;  
    11.     $db = new Functions();  
    12.    $users = $db->getAllUsers();  
    13.    if ($users != false)  
    14.    $no_of_users = mysql_num_rows($users);  
    15.    else  
    16.       $no_of_users = 0;  
    17.    ?>  
    18.    class=“container”>  
    19.       

      No of Devices Registered: echo $no_of_users; ?>

        

    20.       

        
    21.      class=“devices”>  
    22.       
    23.          if ($no_of_users > 0) {  
    24.       ?>  
    25.       
    26.          while ($row = mysql_fetch_array($users)) {  
    27.       ?>  
    28.       
    29.   
    30.       id“] ?>” name=“” method=“post” onsubmit=“return sendPushNotification(‘id“] ?>’)”>  
    31.        echo $row[“name”] ?>  
    32.       class=“clear”>

      

  9.        echo $row[“email”] ?>  
  10.       class=“clear”>

  

  •       class=“send_container”>  
  •          “3” name=“message” cols=“25” class=“txt_message” placeholder=“Type message here”>  
  •          “hidden” name=“regId” value=gcm_regid“] ?>”/>  
  •          “submit” class=“send_btn” value=“Send” onclick=“”/>  
  •       
  •   

  •    

      

  •    
  •   

  • else { ?>  
  •    
  •   
  •       No Users Registered Yet!  
  •    
  •   

  •      
  •    

      

  •    
  •   

  • “http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”> “text/javascript”>  
  •          $(document).ready(function(){  
  •          });  
  •          function sendPushNotification(id){  
  •          var data = $(‘form#’+id).serialize();  
  •          $(‘form#’+id).unbind(‘submit’);  
  •          $.ajax({  
  •             url: “send_pushnotification_message.php”,  
  •             type: ‘POST’,  
  •             data: data,  
  •             success: function(data, textStatus, xhr) {  
  •                $(‘.txt_message’).val(“”);  
  •             },  
  •             error: function(xhr, textStatus, errorThrown) {  
  •             }  
  •          });  
  •          return false;  
  •       }  
  •          
  •   
  • Article Prepared by Ollala Corp

    You might also like More from author

    Leave A Reply

    Your email address will not be published.

    “http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”> “text/javascript”>  
  •          $(document).ready(function(){  
  •          });  
  •          function sendPushNotification(id){  
  •          var data = $(‘form#’+id).serialize();  
  •          $(‘form#’+id).unbind(‘submit’);  
  •          $.ajax({  
  •             url: “send_pushnotification_message.php”,  
  •             type: ‘POST’,  
  •             data: data,  
  •             success: function(data, textStatus, xhr) {  
  •                $(‘.txt_message’).val(“”);  
  •             },  
  •             error: function(xhr, textStatus, errorThrown) {  
  •             }  
  •          });  
  •          return false;  
  •       }  
  •