PHP code for Apple Push Notification Service

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at:

I just lost a week of my life trying to send a message from my server to the APNS servers. A previous team had given us some bad PHP code which I could not get working. I finally tore it out and replaced it with the example I found on StackOverflow:

        /* We are using the sandbox version of the APNS for development. For production
        environments, change this to ssl:// */
        $apnsServer = 'ssl://';
        /* Make sure this is set to the password that you set for your private key
        when you exported it to the .pem file using openssl on your OS X */
        $privateKeyPassword = '1234';
        /* Put your own message here if you want to */
        $message = 'Welcome to iOS 7 Push Notifications';
        /* Pur your device token here */
        $deviceToken =
        /* Replace this with the name of the file that you have placed by your PHP
        script file, containing your private key and certificate that you generated
        earlier */
        $pushCertAndKeyPemFile = 'PushCertificateAndKey.pem';
        $stream = stream_context_create();

        $connectionTimeout = 20;
        $connection = stream_socket_client($apnsServer,
        if (!$connection){
        echo "Failed to connect to the APNS server. Error no = $errorNumber
"; exit; } else { echo "Successfully connected to the APNS. Processing...
"; } $messageBody['aps'] = array('alert' => $message, 'sound' => 'default', 'badge' => 2, ); $payload = json_encode($messageBody); $notification = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; $wroteSuccessfully = fwrite($connection, $notification, strlen($notification)); if (!$wroteSuccessfully){ echo "Could not send the message
"; } else { echo "Successfully sent the message
"; } fclose($connection);