title: APN php code giving Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195
body: <p>I am trying to implement Apple Push Notification using php code. Here's my code</p>
  
  <pre><code>$deviceToken = 'My device token';
  $passphrase = '';
  $message = 'My first push notification!';
  
  ////////////////////////////////////////////////////////////////////////////////
  
  $ctx = stream_context_create();
  stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-dev-cert.pem');
  stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
  
  $fp = stream_socket_client(
      'ssl://gateway.sandbox.push.apple.com:2195', $err,
      $errstr, 120, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
  
  if (!$fp)
      exit("Failed to connect: $err $errstr" . PHP_EOL);
  
  echo 'Connected to APNS' . PHP_EOL;
  
  $body['aps'] = array(
      'alert' =&gt; $message,
      'sound' =&gt; '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;
  
  fclose($fp);
  </code></pre>
  
  <p>The certificate .pem file is in the same directory as the file is.
  This code is running fine on my local machine. I am using MAMP. I am getting notification on my devices.</p>
  
  <p>But when I am trying it on the server, it is not working and giving an error.</p>
  
  <blockquote>
    <p>Warning: stream_socket_client() [function.stream-socket-client]:
    unable to connect to ssl://gateway.sandbox.push.apple.com:2195
    (Connection refused) in
    /home/nextgen/public_html/ApplicationGenerator/appointmentportal/iosapp/SimplePush/simplepush.php
    on line 14 Failed to connect: 111 Connection refused</p>
  </blockquote>
  
  <p>If the certificate file is wrong, how would it work on my local server?</p>
  
  <p>I am not getting any way out of this. Can you guys help me?</p>