0
$passphrase = '';
$deviceToken="8ebf42fd63c37071b9309f938a527189525b777f35571fc249ec1ed2581d3441";
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', "pushCert.pem");
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
{
exit("Failed to connect: $err $errstr" . PHP_EOL);
return 0;
}
// Create the payload body
$body['aps'] = array(
'notification_type_id'=>1,
'contest_id'=>1,
'pic_id'=>1,
'rid'=>1,
'alert' => "Hi John test push",
'sound' => 'default'
);
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
{
echo 'Message not delivered' . PHP_EOL;
}else{
echo 'Message successfully delivered' . PHP_EOL;
} 

Why push notification work sometime and sometime are not? I am getting below warnings when sending a push notification to IOS device

Severity: Warning

Message: fwrite(): SSL operation failed with code 1. OpenSSL Error messages: error:1409F07F:SSL routines:SSL3_WRITE_PENDING:bad write retry

Filename: models/cron_win_contest_model.php

Line Number: 386

Or

Severity: Warning

Message: fwrite(): SSL: Broken pipe

Filename: models/cron_win_contest_model.php

Line Number: 386

Could you please help me to fix this issue

Abhishek Gurjar
  • 7,426
  • 10
  • 37
  • 45
Narendra
  • 1
  • 1

2 Answers2

0

When you are trying to write to the socket. If something goes wrong, fwrite will return false or 0 (depending on the php version) as the return value. When it happens, you must manage it.

By another way, add sleep(5) before fwrite().

You can do something like this :-

try {                           
    $result = fwrite($fp, $msg, strlen($msg));
}
catch (Exception $ex) {
    sleep(5); //sleep for 5 seconds
    $result = fwrite($fp, $msg, strlen($msg));
    if ($result)
    {
        return true;
    }
    else {
        return false;
    }
}

Hope it helps!

Shashank Shah
  • 2,077
  • 4
  • 22
  • 46
0

I m getting the same issue on production and resolve the issue using below steps

Step 1: Change below 
From 
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', 
$err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

To below:   
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', 
$err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

Step 2: add below line just before the "$result = fwrite($fp, $msg, trlen($msg));"

stream_set_blocking($fp, 0);
Govinda Yadav
  • 539
  • 4
  • 14