当前位置:首页 > 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 服务器:

php实现消息通知

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 库发送邮件通知。

php实现消息通知

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']]);

综合方案示例

结合数据库和实时推送的完整流程:

  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
    ]);
}

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

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

相关文章

React如何实现通知

React如何实现通知

React 实现通知的方法 使用状态管理 在 React 组件中通过 useState 或 useReducer 管理通知状态,触发状态更新时显示通知。适合简单场景,无需额外依赖。 import {…

vue实现通知切换

vue实现通知切换

Vue 实现通知切换功能 在 Vue 中实现通知切换功能,可以通过动态绑定类名或样式,结合条件渲染和状态管理来实现。以下是几种常见的方法: 使用 v-if 或 v-show 控制通知显示 通过 v-…

vue实现消息通知功能

vue实现消息通知功能

Vue 实现消息通知功能 使用 Vue 的自定义事件系统 Vue 的自定义事件系统可以用于在组件之间传递消息。通过 $emit 触发事件,$on 监听事件,可以实现简单的消息通知功能。 // 父组件…

vue消息提示怎么实现

vue消息提示怎么实现

Vue 消息提示的实现方法 使用 Element UI 的 Message 组件 Element UI 提供了 ElMessage 组件,用于显示全局消息提示。安装 Element UI 后可以直接使…

php如何实现推送消息推送消息

php如何实现推送消息推送消息

PHP 实现消息推送的方法 使用 WebSocket 实现实时推送 WebSocket 是一种全双工通信协议,适合实时推送消息。PHP 可以与 WebSocket 服务器(如 Ratchet)结合使用…

php实现redis消息队列

php实现redis消息队列

安装 Redis 扩展 确保 PHP 已安装 Redis 扩展。可以通过以下命令安装: pecl install redis 在 php.ini 中添加 extension=redis.so 并重启…