推送通知提供程序内置于PHP

时间:2012-07-09 21:55:21

标签: php iphone mysql ios push-notification

我从互联网上下载了一个用于苹果推送通知的PHP代码,当我将设备令牌值分配给变量时,它正在工作,但是当我编辑这个php代码以从数据库MYSQL获取设备令牌值时,它没有工作:

<?php
// Put your private key's passphrase here:
$passphrase = '123456';

// Put your alert message here:
$message = 'hi push message';

 ////////////////////////////////////////////////////////////////////////////////

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$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</br>' . PHP_EOL;

// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);

// Encode the payload as JSON
$payload = json_encode($body);

////////////////////////////////////////////////////////////////////////
//make global array
$x = array();

function selectfromdb(){
    $con = mysql_connect("localhost","root","root");
    mysql_select_db("my_db", $con);
 mysql_query("set character_set_server='utf8'");
 mysql_query("set names 'utf8'");
 $result = mysql_query("SELECT idip FROM iphoneid");
$c = 0;
while($r = mysql_fetch_array($result))
{
$x[$c] = $r['idip'];
$c++;
}
}
///////////////////////////////////////////////////////////////////////
selectfromdb();
$i = 0;
while ($i < sizeof($x)){
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*',$x[$i]) . pack('n', strlen($payload)) .$payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));


if (!$result)
echo 'Message not delivered</br>' . PHP_EOL;
else
echo 'Message successfully delivered</br>' . PHP_EOL;

$i++;
}
echo 'end</br>';

// Close the connection to the server
fclose($fp);
?>

输出: 连接到APNS 端

1 个答案:

答案 0 :(得分:1)

看起来你需要添加

global $x;在您的顶部选择db函数。尽管让它返回一个值可能会更好。

function selectfromdb(){
    $x = array();
    $con = mysql_connect("localhost","root","root");
    mysql_select_db("my_db", $con);
    mysql_query("set character_set_server='utf8'");
    mysql_query("set names 'utf8'");
    $result = mysql_query("SELECT idip FROM iphoneid");
    $c = 0;
    while($r = mysql_fetch_array($result))
    {
        $x[$c] = $r['idip'];
        $c++;
    }
    return $x;
}