Skip to content

Instantly share code, notes, and snippets.

@everlof
Created January 4, 2017 13:30
Show Gist options
  • Save everlof/5c88bca9b5a48ac74427b4439626ee4d to your computer and use it in GitHub Desktop.
Save everlof/5c88bca9b5a48ac74427b4439626ee4d to your computer and use it in GitHub Desktop.
Send push (PHP)
<?php
// Put your alert message here:
$message = "Message";
$pemfile = $argv[1];
$token = $argv[2];
$subscriptionID = $argv[3];
if (!$subscriptionID)
exit("Example Usage: $php send_push.php [pem-file] [token] [subscriptionID]\n");
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $pemfile);
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
stream_context_set_option($ctx, 'ssl', 'verify_peer_name', false);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'content-available' => 1,
'category' => "DEFAULT_ACTION"
);
// Encode the payload as JSON
$payload = json_encode($body);
print("JSON: ");
print(json_encode($body, JSON_PRETTY_PRINT) . "\n");
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
function getGUID(){
if (function_exists('com_create_guid')){
return com_create_guid();
}else{
mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45);// "-"
$uuid = ''
.substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12);
return $uuid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment