phpapple-push-notificationsapns-php

Push notification work on browser doesn't on commandline


I have php file for running apns. And it does work when i call web page on browser. However it doesn't work on terminal with calling

php deneme.php

I comfirm that .pem file is correctly created. And also determine its location in php file is correct too(because work correctly on browser). I run out with option. I hope you give me an idea.

The deneme.php file is:

<?php
    $apnsServer = 'ssl://gateway.sandbox.push.apple.com:2195';

    $privateKeyPassword = 'MyPassword123';
    $message = 'Test Push Notifications';

    $deviceToken =
    '2877b691ffd9a3edfa45ee31ff25083f1845e016e7902d130eb09713b1c2ed2f';

    $pushCertAndKeyPemFile =  $_SERVER['DOCUMENT_ROOT'].'/ck.pem';// 'ck.pem';
    $stream = stream_context_create();
    stream_context_set_option($stream,
        'ssl',
        'passphrase',
        $privateKeyPassword);
        stream_context_set_option($stream,
        'ssl',
        'local_cert',
        $pushCertAndKeyPemFile);

    $connectionTimeout = 20;
    $connectionType = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
    $connection = stream_socket_client($apnsServer,
    $errorNumber,
    $errorString,
    $connectionTimeout,
    $connectionType,
    $stream);
    if (!$connection){
        echo "Failed to connect to the APNS server. Error no = $errorNumber<br/>";
        exit;
    } else {
        echo "Successfully connected to the APNS. Processing...</br>";
    }
    $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<br/>";
    }
    else {
        echo "Successfully sent the message<br/>";
    }
    fclose($connection);
?>

Solution

  • There are no $_SERVER[] superglobals available when running from CLI, since there is no server running. Replace$_SERVER['DOCUMENT_ROOT'].'/ck.pem'; with the absolute path to your ck.pem file.