Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save manjeshpv/d5b8e271af94824836d9 to your computer and use it in GitHub Desktop.
Save manjeshpv/d5b8e271af94824836d9 to your computer and use it in GitHub Desktop.
Apple Push Notification APNS PHP Snippet - Server Side Implementation
<?php
$deviceToken = '6e1326c0e4758b54332fab3b3cb2f9ed92e2cd332e9ba8182f49027054b64d29'; // iPad 5s Gold prod
$passphrase = '';
$message = 'Hello Push Notification';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'pushcert.pem'); // Pem file to generated // openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts // .p12 private key generated from Apple Developer Account
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); // production
// $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); // developement
echo "<p>Connection Open</p>";
if(!$fp){
echo "<p>Failed to connect!<br />Error Number: " . $err . " <br />Code: " . $errstrn . "</p>";
return;
} else {
echo "<p>Sending notification!</p>";
}
$body['aps'] = array('alert' => $message,'sound' => 'default','extra1'=>'10','extra2'=>'value');
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
//var_dump($msg)
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo '<p>Message not delivered ' . PHP_EOL . '!</p>';
else
echo '<p>Message successfully delivered ' . PHP_EOL . '!</p>';
fclose($fp);
?>
@FarhanKhalid
Copy link

Thank you. Simple, concise and works!

@srjlulla
Copy link

gateway.push.apple.com:2195 won't work anymore

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment