消息通知 php实现
消息通知的 PHP 实现
使用数据库存储通知
在数据库中创建通知表,包含字段如 id、user_id、message、is_read 和 created_at。通过 PHP 插入新通知记录,查询未读通知数量并标记为已读。
// 插入新通知
$stmt = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
$stmt->execute([$userId, $message]);
// 查询未读通知
$stmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
$stmt->execute([$userId]);
$unreadCount = $stmt->fetchColumn();
使用 Session 或 Cookie 实现简单通知
对于临时通知,可以使用 Session 或 Cookie 存储消息并在页面加载时显示。
// 设置通知
$_SESSION['notification'] = 'Your action was successful!';
// 显示通知
if (isset($_SESSION['notification'])) {
echo '<div class="alert">' . $_SESSION['notification'] . '</div>';
unset($_SESSION['notification']);
}
实时通知推送
结合 WebSocket 或 AJAX 轮询实现实时通知。使用 Pusher 或其他实时通信服务推送通知到客户端。
// 使用 Pusher 发送实时通知
require 'vendor/autoload.php';
$pusher = new Pusher\Pusher($key, $secret, $app_id, $options);
$pusher->trigger('notifications', 'new-notification', ['message' => $message]);
邮件通知
通过 PHP 的 mail() 函数或第三方库如 PHPMailer 发送邮件通知。
$to = 'user@example.com';
$subject = 'New Notification';
$message = 'You have a new notification.';
$headers = 'From: webmaster@example.com';
mail($to, $subject, $message, $headers);
集成第三方服务
使用 Firebase Cloud Messaging (FCM) 或 Twilio 发送移动推送或短信通知。

// 使用 FCM 发送推送通知
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = [
'to' => '/topics/notifications',
'notification' => ['title' => 'New Message', 'body' => $message]
];
$headers = ['Authorization: key=YOUR_API_KEY', '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($fields));
$result = curl_exec($ch);
curl_close($ch);






