我正在开发一个 PHP 脚本,该脚本通过 IMAP 定期检查用户的收件箱是否有新消息。该脚本与 IMAP 服务器保持开放连接,并每 5 秒获取最新消息的 UID。如果 UID 大于最初记录的比较 UID,则脚本向用户的 iPhone 发送推送通知,通知他/她有新消息可用,将新 UID 记录为比较 UID,并继续检查新消息以这种方式。这是脚本:
<?php
$server = '{imap.gmail.com:993/ssl}';
$login = 'email_address@gmail.com';
$password = 'my_email_password';
$connection = imap_open($server, $login, $password) OR die ("can't connect: " . imap_last_error());
$imap_obj = imap_check($connection);
$number = $imap_obj->Nmsgs;
$uid = imap_uid($connection, $number);
//infinite loop, need to add some sort of escape condition...
for(;;){
$imap_obj = imap_check($connection);
$number = $imap_obj->Nmsgs;
//if there is a new message send push notification
if(imap_uid($connection, $number) > $uid){
$uid = imap_uid($connection, $number);
$result = imap_fetch_overview($connection,$number,0);
$message = $result[0]->subject;
$deviceToken = 'xxxxxxxxxxxxxxxxxx';
$passphrase = 'my_secret_password';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
//echo 'Message not delivered' . PHP_EOL;
else
//echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
}
sleep(5);
}
imap_close($connection);
?>
这行得通。但这对我来说似乎非常低效。每个额外的用户都与 IMAP 服务器保持无限连接,并每隔几秒钟检查一次新消息,这似乎很愚蠢。
有一个更好的方法吗?