If you are developing you so many time need a PHP code to send the push notification on android devices. Learn here how to send push notification in PHP to an android device.
Before sending the push we need Google API key for validation. You can generate the Google API key from your Google account.
You also need an array of device tokens of android devices for you wanted to send the push notifications.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
<?php
class SendGCMNotification
{
/**
* Sending GCM Push Notification
*/
public function sendPushNotification($registatoin_ids, $data) {
$GOOGLE_API_KEY = "BAIzyBUHHlX4i8na4HDHLCqKz0wTSY8ITsmI3Ud";
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $data,
);
$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);
}
}
$gcm_obj = new SendGCMNotification();
$registatoin_ids = array('device_token1','device_token2','device_token3');
$data = array('subject'=>'tsting','message'=>'www.coding4developers.com');
$gcm_obj->sendPushNotification($registatoin_ids, $data);
?>
|