php实现消息通知
PHP 实现消息通知的方法
使用数据库存储通知
在数据库中创建通知表,包含字段如 id、user_id、message、is_read 和 created_at。通过 SQL 插入新通知,用户登录时查询未读通知。
CREATE TABLE notifications (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
message TEXT NOT NULL,
is_read BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
PHP 插入通知示例:
$message = "您有一条新消息";
$userId = 1;
$stmt = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
$stmt->execute([$userId, $message]);
使用 Session 或 Cookie 存储临时通知
对于一次性通知如操作成功提示,可使用 Session 存储并在页面显示后清除。
session_start();
$_SESSION['notification'] = "操作成功";
// 在页面显示后
unset($_SESSION['notification']);
使用 WebSocket 实现实时通知
结合前端技术如 WebSocket,实现服务器主动推送。需要 Ratchet 等 PHP WebSocket 库。
安装 Ratchet:
composer require cboden/ratchet
创建 WebSocket 服务器:
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\NotificationHandler;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new NotificationHandler()
)
),
8080
);
$server->run();
使用第三方服务
集成第三方通知服务如 Firebase Cloud Messaging (FCM) 或 Pusher,实现跨平台推送。
Pusher 示例:
require __DIR__ . '/vendor/autoload.php';
$pusher = new Pusher\Pusher(
"APP_KEY",
"APP_SECRET",
"APP_ID",
['cluster' => 'APP_CLUSTER']
);
$pusher->trigger('notifications', 'new_message', [
'message' => 'Hello World'
]);
邮件通知
通过 PHP 内置 mail() 函数或 PHPMailer 库发送邮件通知。
PHPMailer 示例:
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->setFrom('from@example.com');
$mail->addAddress('to@example.com');
$mail->Subject = '通知标题';
$mail->Body = '通知内容';
$mail->send();
浏览器推送通知
使用 Service Worker 和 Push API 实现浏览器推送,PHP 后端处理订阅和触发。
保存订阅信息到数据库:
$subscription = json_decode(file_get_contents('php://input'), true);
$stmt = $pdo->prepare("INSERT INTO push_subscriptions (endpoint, public_key, auth_token) VALUES (?, ?, ?)");
$stmt->execute([$subscription['endpoint'], $subscription['keys']['p256dh'], $subscription['keys']['auth']]);
综合方案示例
结合数据库和实时推送的完整流程:
- 用户操作触发 PHP 生成通知并存入数据库
- 通过 WebSocket 或 Pusher 实时推送给在线用户
- 离线用户下次登录时从数据库拉取未读通知
- 重要通知通过邮件或浏览器推送补充送达
// 生成通知
function createNotification($userId, $message) {
global $pdo;
$stmt = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
$stmt->execute([$userId, $message]);
// 实时推送
$pusher->trigger('user_' . $userId, 'new_notification', [
'message' => $message
]);
}
以上方法可根据项目需求单独或组合使用,实现灵活的消息通知系统。







