php聊天实现
PHP 聊天实现方法
使用 WebSocket 实现实时聊天
安装 Ratchet 库(PHP WebSocket 库):
composer require cboden/ratchet
创建 WebSocket 服务器脚本:
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
创建聊天处理类:
namespace MyApp;
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) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
前端 HTML/JavaScript 代码:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
</head>
<body>
<div id="chat"></div>
<input type="text" id="msg" />
<button onclick="sendMsg()">Send</button>
<script>
const conn = new WebSocket('ws://localhost:8080');
conn.onmessage = e => {
document.getElementById('chat').innerHTML += e.data + '<br>';
};
function sendMsg() {
const msg = document.getElementById('msg').value;
conn.send(msg);
document.getElementById('msg').value = '';
}
</script>
</body>
</html>
使用 AJAX 轮询实现简单聊天
PHP 后端处理(chat.php):
<?php
$file = 'chatlog.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$message = $_POST['message'] . "\n";
file_put_contents($file, $message, FILE_APPEND);
exit;
}
echo file_exists($file) ? file_get_contents($file) : '';
前端实现:

<div id="chat"></div>
<input type="text" id="message">
<button onclick="sendMessage()">Send</button>
<script>
function sendMessage() {
const message = document.getElementById('message').value;
fetch('chat.php', {
method: 'POST',
body: new URLSearchParams({message: message})
});
document.getElementById('message').value = '';
}
setInterval(() => {
fetch('chat.php')
.then(response => response.text())
.then(text => {
document.getElementById('chat').innerHTML = text.replace(/\n/g, '<br>');
});
}, 1000);
</script>
使用数据库存储聊天记录
创建 MySQL 表:
CREATE TABLE chat_messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
PHP 数据库操作类:
class ChatDB {
private $pdo;
public function __construct() {
$this->pdo = new PDO('mysql:host=localhost;dbname=chat', 'username', 'password');
}
public function saveMessage($username, $message) {
$stmt = $this->pdo->prepare("INSERT INTO chat_messages (username, message) VALUES (?, ?)");
$stmt->execute([$username, $message]);
}
public function getMessages() {
$stmt = $this->pdo->query("SELECT * FROM chat_messages ORDER BY created_at DESC LIMIT 50");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
实现用户认证
用户登录处理:

session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
if (authenticateUser($username, $password)) {
$_SESSION['username'] = $username;
header('Location: chat.php');
exit;
}
}
function authenticateUser($username, $password) {
// 实现实际认证逻辑
return true; // 示例代码
}
聊天页面检查登录:
session_start();
if (!isset($_SESSION['username'])) {
header('Location: login.php');
exit;
}
$username = $_SESSION['username'];
安全注意事项
验证和过滤所有用户输入:
$message = htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8');
防止 SQL 注入:
$stmt = $pdo->prepare("INSERT INTO messages (user, content) VALUES (?, ?)");
$stmt->execute([$user, $content]);
设置适当的 CORS 头(如需要):
header("Access-Control-Allow-Origin: http://yourdomain.com");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: Content-Type");






