php实现推送功能实现
PHP 实现推送功能的方法
推送功能通常用于实时通知用户,可以通过多种技术实现。以下是几种常见的 PHP 推送实现方式:
使用 WebSocket 实现实时推送
WebSocket 是一种全双工通信协议,适合实时推送场景。PHP 可以通过 Ratchet 库实现 WebSocket 服务端。
安装 Ratchet:
composer require cboden/ratchet
创建 WebSocket 服务端:
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
创建 Chat 类处理消息:
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
使用 Server-Sent Events (SSE)
SSE 是 HTML5 标准的一部分,允许服务器向浏览器推送事件。
PHP 实现 SSE 服务端:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
function sendMsg($id, $msg) {
echo "id: $id\n";
echo "data: $msg\n\n";
ob_flush();
flush();
}
while(true) {
$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", $serverTime));
sleep(1);
}
客户端 JavaScript 接收 SSE:
const evtSource = new EventSource("sse.php");
evtSource.onmessage = function(e) {
console.log(e.data);
};
使用长轮询 (Long Polling)
长轮询是传统轮询的改进版,服务器在有新数据时才响应。
PHP 长轮询实现:
$lastEventId = isset($_GET['lastEventId']) ? $_GET['lastEventId'] : 0;
while(true) {
$newData = checkForNewData($lastEventId);
if($newData) {
echo json_encode($newData);
break;
}
sleep(1);
}
function checkForNewData($lastId) {
// 查询数据库或其他数据源
return $data; // 返回新数据或false
}
使用第三方推送服务
对于移动应用推送,可以使用 Firebase Cloud Messaging (FCM) 或 Apple Push Notification Service (APNS)。

PHP 发送 FCM 通知示例:
function sendFCM($token, $title, $body) {
$url = 'https://fcm.googleapis.com/fcm/send';
$serverKey = 'YOUR_SERVER_KEY';
$notification = [
'title' => $title,
'body' => $body,
'icon' => 'ic_notification',
'sound' => 'default'
];
$data = [
'registration_ids' => [$token],
'notification' => $notification
];
$headers = [
'Authorization: key=' . $serverKey,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
使用消息队列实现异步推送
对于高并发场景,可以使用 RabbitMQ、Redis 等消息队列。
PHP 使用 Redis 发布/订阅示例:
发布消息:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->publish('channel', 'message');
订阅消息:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->subscribe(['channel'], function($redis, $channel, $message) {
echo "Received $message from $channel\n";
});
选择推送方案的考虑因素
- 实时性要求:WebSocket 和 SSE 适合高实时性场景
- 客户端支持:Web 端优先考虑 WebSocket 或 SSE,移动端考虑 FCM/APNS
- 服务器资源:长轮询比 WebSocket 消耗更多资源
- 开发复杂度:第三方服务简化开发但可能有成本
以上方法可根据具体需求组合使用,例如 WebSocket 处理实时聊天,FCM 处理移动推送通知。






