Page 1 of 1

apple push service with php scripts

Posted: Mon Aug 10, 2009 5:57 am
by bobbiesimpson
I'm trying to code a php script that will send push notifications to the Apple Push Service that eventually get delivered to specific iphone devices. The problem I'm having is related to how I connect to apple's push services through a socket since it says very specifically that if I wish to send multiple messages then I should not be connecting and disconnecting rapidly since this may be considered a denial of service attack. So I wish to hold a connection for a certain length of time, and if I have no messages to send after this time is up, then I will disconnect.

I grabbed some code from http://blog.boxedice.com/2009/07/10/how ... -tutorial/ but it's clear that this is not the best solution. This is the code I'm using

Code: Select all

 
 
$deviceToken = '123456'; // masked for security reason
 
$alert = array( 'body' => 'tester', 'action-loc-key' => null);
$body['aps'] = array('alert' => $alert, 'badge' => 1, 'sound' => 'default' );
/* End of Configurable Items */
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-dev.pem');
// assume the private key passphase was removed.
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
print "Failed to connect". $err;
return;
}
else {
print "Connection OKn";
}
$payload = json_encode($body);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
$msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
print "sending message :" . $payload . "n";
fwrite($fp, $apnsMessage);
socket_close($fp);
fclose($fp);
How would I modify this to keep the connection open say, for 5 mins even when I execute the script again? I'm sorry for my lack of understanding but I'm keen to learn!

Rob