php实现在线客服
PHP实现在线客服系统
在线客服系统通常需要实时通信功能,可通过PHP结合WebSocket或长轮询实现。以下是几种常见实现方式:
使用WebSocket实现实时通信
安装Ratchet库(PHP WebSocket库):
composer require cboden/ratchet
创建WebSocket服务器(server.php):
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();
创建聊天处理类(MyApp/Chat.php):
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) {
$client->send($msg);
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
前端实现
HTML/JavaScript客户端代码:
<div id="chat-box" style="height:300px;overflow-y:scroll;"></div>
<input type="text" id="message" placeholder="输入消息">
<button onclick="sendMessage()">发送</button>
<script>
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = function(e) {
document.getElementById('chat-box').innerHTML += '<div>'+e.data+'</div>';
};
function sendMessage() {
const msg = document.getElementById('message').value;
ws.send(msg);
document.getElementById('message').value = '';
}
</script>
使用AJAX长轮询实现
客服端PHP脚本(polling.php):
session_start();
$lastMsgId = $_SESSION['last_msg_id'] ?? 0;
// 模拟从数据库获取新消息
$newMessages = getNewMessagesFromDB($lastMsgId);
if (!empty($newMessages)) {
$_SESSION['last_msg_id'] = end($newMessages)['id'];
echo json_encode($newMessages);
exit;
}
// 无新消息时等待
sleep(10);
echo json_encode([]);
前端JavaScript轮询代码:
function pollMessages() {
fetch('polling.php')
.then(response => response.json())
.then(messages => {
if (messages.length > 0) {
// 显示新消息
messages.forEach(msg => {
displayMessage(msg);
});
}
pollMessages(); // 继续轮询
});
}
// 启动轮询
pollMessages();
数据库设计示例
创建消息表SQL:
CREATE TABLE `chat_messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sender_id` int(11) NOT NULL,
`receiver_id` int(11) NOT NULL,
`message` text NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_read` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
实现用户状态管理
用户在线状态表:
CREATE TABLE `user_status` (
`user_id` int(11) NOT NULL,
`is_online` tinyint(1) NOT NULL DEFAULT '0',
`last_active` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`)
);
更新用户状态的PHP代码:
function updateUserStatus($userId, $isOnline) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("REPLACE INTO user_status (user_id, is_online) VALUES (?, ?)");
$stmt->execute([$userId, $isOnline ? 1 : 0]);
}
安全考虑
验证用户身份:
function verifyUser($token) {
// 验证JWT或其他身份验证令牌
// 返回用户ID或false
}
过滤消息内容:
function sanitizeMessage($message) {
$message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
return strip_tags($message);
}
以上方案可根据实际需求进行组合和扩展,WebSocket适合高实时性要求场景,而AJAX轮询更适合简单实现。数据库设计可根据业务需求调整,如增加客服分组、对话记录等功能。






