我工作的一个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服务器检查新邮件每隔几秒钟,这似乎傻无限期连接,和。
有一个更好的方法吗? 要么例如PHP代码/链接代码(这将是理想的,我会永远爱你)或抽象的术语(这将产生类似的还少无条件崇拜)有人可以解释最佳实践,这种任务的?
谢谢! 詹姆士