Send Push Notification To Android App Using PHP

- First Create a Google GCM API on Google Developer.
- Create this file (GCM.php)

<?php

class GCM {
//put your code here
// constructor
function __construct() {
} /**
* Sending Push Notification
*/
function send_gcm_notification($registatoin_ids, $message) {
// include config
// Set POST variables $url = 'https://android.googleapis.com/gcm/send';

$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message
);
$headers = array(
'Authorization: key= YOUR_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;
}
}
?>



- At you PHP file you want to send Push Notification, Just call function we created as below:

$message=“MESSAGE_YOU_WANT_TO_SEND”;
$subject=“MESSAGE_SUBJECT”;
$created= $date->format('Y-m-d H:i:s');
$regId =“YOU_DEVICE_ID”;
$registatoin_ids = array($regId);
$message = array("title" => $subject,"message" => $body,"created_at" => $created);
$gcm = new GCM();
$result = $gcm->send_gcm_notification($registatoin_ids, $message);


- This will call function we created first then send push notification to device ID given.

Popular Posts