php实现在线交流功能
实现基础聊天功能
使用PHP结合WebSocket或Ajax轮询实现实时通信。WebSocket更高效但需要服务器支持,Ajax轮询兼容性更好但资源消耗较大。
WebSocket服务器示例(需安装Ratchet库):
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
$client->send($msg);
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
数据库存储消息
创建MySQL表存储聊天记录:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
PHP消息存储示例:

$pdo = new PDO('mysql:host=localhost;dbname=chat', 'username', 'password');
$stmt = $pdo->prepare("INSERT INTO messages (user_id, content) VALUES (?, ?)");
$stmt->execute([$userId, $message]);
前端界面实现
使用JavaScript处理实时消息显示:
const socket = new WebSocket('ws://yourserver:8080');
socket.onmessage = function(e) {
const chatBox = document.getElementById('chat-box');
chatBox.innerHTML += `<div>${e.data}</div>`;
};
function sendMessage() {
const input = document.getElementById('message-input');
socket.send(input.value);
input.value = '';
}
用户认证与安全
实现基本的用户认证系统:
session_start();
function authenticate($username, $password) {
// 验证逻辑
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
}
function isAuthenticated() {
return isset($_SESSION['user_id']);
}
消息发送前的XSS过滤:

function sanitizeMessage($message) {
return htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
}
扩展功能实现
添加私聊功能数据库表:
CREATE TABLE private_messages (
id INT AUTO_INCREMENT PRIMARY KEY,
sender_id INT,
receiver_id INT,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
消息已读状态追踪:
ALTER TABLE private_messages ADD COLUMN is_read BOOLEAN DEFAULT FALSE;
实现消息推送通知:
Notification.requestPermission().then(perm => {
if (perm === "granted") {
new Notification("新消息", {body: message});
}
});






