php实现推送
PHP 实现推送的方法
PHP 可以通过多种方式实现推送功能,包括服务器推送(Server-Sent Events)、WebSocket、长轮询(Long Polling)以及第三方推送服务(如 Firebase Cloud Messaging)。以下是几种常见的方法:
使用 Server-Sent Events (SSE)
SSE 是一种基于 HTTP 的服务器推送技术,适用于单向实时通信(服务器到客户端)。
// 服务器端代码
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
while (true) {
$data = json_encode(['time' => date('H:i:s')]);
echo "data: {$data}\n\n";
ob_flush();
flush();
sleep(1);
}
客户端通过 JavaScript 监听事件:
const eventSource = new EventSource('sse.php');
eventSource.onmessage = function(e) {
console.log(e.data);
};
使用 WebSocket
WebSocket 支持全双工通信,适合需要双向交互的场景。PHP 可以通过 Ratchet 等库实现 WebSocket 服务。
安装 Ratchet:

composer require cboden/ratchet
服务器端代码:
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();
客户端通过 JavaScript 连接:
const socket = new WebSocket('ws://localhost:8080');
socket.onmessage = function(e) {
console.log(e.data);
};
使用长轮询 (Long Polling)
长轮询通过保持 HTTP 连接直到有数据返回,模拟实时推送。

服务器端代码:
// 检查是否有新数据
$newData = checkForNewData(); // 自定义逻辑
if ($newData) {
echo json_encode($newData);
} else {
sleep(5); // 等待 5 秒后重新检查
}
客户端通过 AJAX 轮询:
function poll() {
fetch('poll.php')
.then(response => response.json())
.then(data => {
console.log(data);
poll(); // 递归调用
});
}
poll();
使用第三方推送服务
例如 Firebase Cloud Messaging (FCM),适用于移动端和 Web 端推送。
发送推送的 PHP 代码:
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = [
'Authorization: key=YOUR_SERVER_KEY',
'Content-Type: application/json'
];
$data = [
'to' => 'DEVICE_TOKEN',
'notification' => [
'title' => 'Test Push',
'body' => 'This is a test message'
]
];
$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);
echo $result;
注意事项
- 性能优化:SSE 和 WebSocket 适合高并发场景,长轮询会增加服务器负载。
- 兼容性:SSE 不支持 IE,WebSocket 需要现代浏览器支持。
- 安全性:使用 WebSocket 时需注意防止跨站攻击(如验证 Origin 头)。
根据具体需求选择合适的方法,SSE 和 WebSocket 是推荐的高效方案。






