Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active October 30, 2016 18:15
Show Gist options
  • Save surferxo3/1bc2ad95967aea171f935fc68e120652 to your computer and use it in GitHub Desktop.
Save surferxo3/1bc2ad95967aea171f935fc68e120652 to your computer and use it in GitHub Desktop.
Script to send iOS and Android Push Notifications.
<?php
/*#############################
* Developer: Mohammad Sharaf Ali
* Designation: Web Developer
* Version: 1.0
*/#############################
#function to send push notification
function sendPush($deviceToken, $body, $type, $params) {
$result = '';
if ($type == 'ios') {
if ($deviceToken != '(null)') { // null device token when ios user don't opt for push notification permission
$passphrase = $params['pass_phrase'];
$url = $params['url']; // ssl://gateway.sandbox.push.apple.com:2195
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'path/to/your/ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client($url, $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
/*
if (!$fp) {
exit("Failed to connect: $err $errstr" . PHP_EOL);
}
*/
/* sample data
$body['aps'] = array('alert' => 'Hello to the future!',
'sound' => 'default',
'badge' => 1
);
$body['Data'] = array('custom_key' => 'custom_value');
*/
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
fclose($fp);
}
} else if ($type == 'android') {
if (!is_null($deviceToken)) {
$google_api_key = $params['google_api_key'];
$url = $params['url']; // https://android.googleapis.com/gcm/send
/* sample data
$body = array('custom_key' => 'custom_value'],
'price' => 'Hello to the future!');
*/
$fields = array(
'registration_ids' => array($deviceToken), // can be single or array of device tokens
'data' => $body);
$headers = array('Authorization: key=' . $google_api_key,
'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
/*
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
*/
curl_close($ch);
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment