0

I'm using the following code to cycle through a database containing the device ID's that my ios app collects. At around 300 or so notifications my server freezes in a 500 error. Any ideas how I can do this more efficiently? I am on a shared server; would my only option be to set this up on a dedicated machine?

php.ini has the following set -

set_time_limit = 999999999
max_execution_time = 999999999
memory_limit = 512M

Here's the code -

if(isset($_POST['pushNotify'])){ /// PROCESS PUSH NOTIFICATION TO LAST 120 DAYS OF ACTIVE USERS
$message = stripslashes(strip_tags(trim($_POST['message'])));

mysql_connect("URL", "USER", "PASS") or die(mysql_error());
mysql_select_db("DATABASE") or die(mysql_error());
$cutoff = time() - (60*60*24*120);
$result = mysql_query("SELECT * FROM devices WHERE timestamp > '$cutoff' ORDER BY timestamp DESC");
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', '../certs/distck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', 'password');
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

while($row = mysql_fetch_array($result))
  {
  if(strlen(trim($row['deviceid']))>25){
    $devid = str_replace("-", "", trim($row['deviceid']));
    $payload = '{
                    "aps" : 

                        { "alert" : "'.$message.'",
                          "badge" : 0,
                          "sound" : "bingbong.aiff"
                        } 
                }';


    $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $devid)) . pack      ("n",strlen($payload)) . $payload;
    if(!@fwrite($fp, $msg)){
        @fclose($fp);
        $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        @fwrite($fp, $msg);
        }
    }
    @fclose($fp);

} /// END PUSH NOTIFY
4

1 回答 1

1

我建议您删除 @ 符号。!@fwrite应该避免。如果 fwrite 失败或连接被切断,则fwrite返回 FALSE,这正是您需要知道的。提醒:一旦出现任何错误,Apple 就会断开连接。

问题:

  1. 如果 fwrite 失败,你有正确的想法:关闭套接字,重新打开,再试一次;除了如果您发送无效令牌,Apple 可以关闭连接(这通常是由于多种原因)。因此,您不应重试相同的令牌,而应继续进行下一个令牌。

  2. 如果 fwrite 第二次失败(在您的重试条件下),您不会捕获错误,此时您没有打开套接字,这可能会解释您的 500 错误。考虑重新编写逻辑以在继续之前重试 N 次。

如果您使用二进制接口(这是 Apple 现在推荐的),您实际上可以从 Apple 获得准确的错误通知。您可以在此处阅读更多相关信息。

于 2013-11-06T08:12:25.677 回答