Sending APNS to thousands of php devices taking too long

I am sending APNS to multiple devices in PHP in a loop.

while($row = mysql_fetch_array($result))
  {
    $row['devicetoken'];
    $row['devcertificate'];
    $row['prodcertificate'];

    if($devprod=="dev"){
        $apnsserverurl="ssl://gateway.sandbox.push.apple.com:2195";
        $certificatename=$appname."".$row['devcertificate'];
    }
    elseif($devprod=="prod"){
        $apnsserverurl="ssl://gateway.push.apple.com:2195";
        $certificatename=$appname."".$row['prodcertificate'];
    }
    sendpush($row['devicetoken'],$certificatename,$apnsserverurl);
  }

Here is the push send function:

function sendpush($deviceToken,$certificatename,$apnsserverurl){
// Get the parameters from http get or from command line
$message = utf8_encode(urldecode($_POST['message']));
$badge = 0;
$sound = "";
// Construct the notification payload
$body = array();
$body['aps'] = array('alert' => $message);
if ($badge)
$body['aps']['badge'] = $badge;
if ($sound)
$body['aps']['sound'] = $sound;
/* End of Configurable Items */



$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $certificatename);

$fp = stream_socket_client($apnsserverurl, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
    //print "Failed to connect $err";
    return;
}
else {
    //print "Connection OK";
}
$payload = json_encode($body);
$msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
print "sending message :" . $payload . "n";
fwrite($fp, $msg);
fclose($fp);   
}

The problem that is being encountered is that it takes too much time. How can I optimize the code?


Finally, I use https://code.google.com/p/apns-php/ , which make only 1 connection and send messages

+4
source share
3 answers

APN Best Practices requires your server connection to open:

. push-, . : push- APN .

APN ; dont . APN . , , , , , .

Apple, , DoS- .

+5

hylander0 . . , , , SSL- , . Apple , .

stream_context_create() sendPush , sendPush ( fwrite(). Apple push-, , .

, , pushtoken , , fwrite , .

+3

, stream_socket_client() . fwrite() .

+1

All Articles