当前位置:首页 > PHP

php实现消息通知

2026-02-16 07:43:02PHP

PHP 实现消息通知的方法

使用数据库存储通知

在数据库中创建通知表,包含字段如 iduser_idmessageis_readcreated_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实现消息通知

  1. 用户操作触发 PHP 生成通知并存入数据库
  2. 通过 WebSocket 或 Pusher 实时推送给在线用户
  3. 离线用户下次登录时从数据库拉取未读通知
  4. 重要通知通过邮件或浏览器推送补充送达
// 生成通知
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
    ]);
}

以上方法可根据项目需求单独或组合使用,实现灵活的消息通知系统。

标签: 消息通知
分享给朋友:

相关文章

vue实现消息通告

vue实现消息通告

Vue 实现消息通告的方法 消息通告通常用于展示系统通知、公告或提示信息。以下是几种常见的实现方式: 使用 Vue 原生组件 通过 Vue 的 v-if 或 v-show 控制消息通告的显示与隐藏:…

vue消息提醒实现

vue消息提醒实现

vue消息提醒实现 在Vue中实现消息提醒功能,可以通过以下几种方式: 使用Element UI的Notification组件 Element UI提供了Notification组件,可以快速实现消…

vue实现消息无缝滑动

vue实现消息无缝滑动

Vue 实现消息无缝滑动的方法 使用 CSS 动画实现基础滑动 通过 CSS 的 transition 或 animation 属性实现消息的平滑移动效果。将消息列表包裹在一个容器中,通过改变容器的…

vue实现发送语音消息

vue实现发送语音消息

实现语音消息的基本流程 在Vue中实现语音消息功能通常涉及录音、音频处理和发送三个核心环节。需要使用浏览器提供的Web Audio API和MediaRecorder API,结合前端框架的特性完成开…

react消息订阅性能如何

react消息订阅性能如何

React 消息订阅性能分析 React 的消息订阅性能通常与实现方式、数据流规模以及优化策略有关。以下是关键点: 原生 Context API 性能 Context 的更新会触发所有订阅…

php通知实现

php通知实现

PHP 实现通知功能的方法 使用数据库存储通知 在数据库中创建通知表,包含字段如 id, user_id, message, is_read, created_at。通过 SQL 插入和查询实现通知的…