Cuelogic Blog Icon
Cuelogic Career Icon
Home > Blog > All > Google cloud messaging with PHP

Google cloud messaging with PHP

Google Cloud Messaging for Android (GCM) is a free service that allows you to send data from your server to your users’ Android device, and also to receive messages from devices on the same connection.

GCM allows data provider servers to send messages to their Android applications. GCM simply passes message data to application, app receives data now application has full control of how to handle it. For example, the application might post a notification, display a custom user interface, or silently sync data. It requires devices running Android 2.2 or higher that also have the Google Play Store application installed. Good news is to test this developer do not require device, we can test it from emulator also however emulator should run on Android 2.2.

GCM

How to send GCM using PHP?

1. Create project on GCMand define API key in PHP file.

<?php
/*
 * Google API Key
 */
define("GOOGLE_API_KEY", "BIzaSyCRLa4LQZWNQBcRCYcIVYA45i9i8zfClqc"); // Place your Google API Key
?>

2. Create a class to send message

<?php
 
class GCM {
 
 //put your code here
 // constructor
 function __construct() {
 
 }
 
 /**
 * Sending Push Notification
 */
 public function send_notification($message) {
 
 // Set POST variables
 $url = 'https://android.googleapis.com/gcm/send';
 
 $fields = array(
 'data' => $message,
 );
 
 $headers = array(
 'Authorization: key=' . GOOGLE_API_KEY,
 'Content-Type: application/json'
 );
 // Open connection
 $ch = curl_init();
 
 // Set the url, number of POST vars, POST data
 curl_setopt($ch, CURLOPT_URL, $url);
 
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
 // Disabling SSL Certificate support temporarly
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 
 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
 
 // Execute post
 $result = curl_exec($ch);
 if ($result === FALSE) {
 die('Curl failed: ' . curl_error($ch));
 }
 
 // Close connection
 curl_close($ch);
 echo $result;
 }
 
}
 
?>

3. Include class in you project and start sending notification to Android devices

<?php
if (isset($_GET["message"])) {
 $message = $_GET["message"];
 
 $gcm = new GCM();
 
 $result = $gcm->send_notification($message);
 
 echo $result;
}
?>