fazlurr
4/16/2015 - 12:06 PM

Send Push Notification with PHP via APNS - http://stackoverflow.com/a/5638338/4549947

Send Push Notification with PHP via APNS - http://stackoverflow.com/a/5638338/4549947

// From : http://stackoverflow.com/a/17022525/4549947

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ckipad.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

$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 amarnew: $err $errstr" . PHP_EOL);

//echo 'Connected to APNS' . PHP_EOL;

// Create the payload body
$body['aps'] = array(
    'badge' => +1,
    'alert' => $message,
    'sound' => 'default'
);

$payload = json_encode($body);

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . 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 amar'.$message. PHP_EOL;

// Close the connection to the server
fclose($fp);
$apnsHost = '<APNS host>';
$apnsPort = <port num>;
$apnsCert = '<cert>';

$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);

$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

$payload['aps'] = array('alert' => 'some notification', 'badge' => 0, 'sound' => 'none');
$payload = json_encode($payload);

// Note: $device_tokens_array has list of 5 devices' tokens

for($i=0; $i<5; $i++)
{
    $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_tokens_array[i])) . chr(0) . chr(strlen($payload)) . $payload;

    fwrite($apns, $apnsMessage);
}?>