Backend Development 6 min read

Building a Simple Real-Time Chat System with PHP, MySQL, AJAX, and WebSocket

This tutorial explains how to create a basic real-time chat application by combining PHP backend logic, MySQL storage, AJAX polling, and WebSocket communication to enable instant message exchange in web browsers.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Building a Simple Real-Time Chat System with PHP, MySQL, AJAX, and WebSocket

Real-time chat systems are essential for web chat rooms, online customer service, and collaborative tools; this article demonstrates how to build a simple real-time chat application using PHP, MySQL, AJAX, and WebSocket.

Implementation Overview

We store user messages and information in a MySQL database, use PHP as the server backend to process requests, employ AJAX for asynchronous data exchange, and leverage WebSocket for bidirectional real-time communication.

HTML Frontend

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>实时聊天系统</title>
</head>
<body>
  <div>
    <div id="messages"><!-- chat history will appear here --></div>
    <input type="text" id="message" />
    <button id="send">发送</button>
  </div>
  <script type="text/javascript">
    var conn = new WebSocket('ws://localhost:8080');
    conn.onopen = function(e) { console.log("连接已建立!"); };
    conn.onmessage = function(e) { console.log(e.data); };
  </script>
</body>
</html>

JavaScript WebSocket Client

document.getElementById('send').addEventListener('click', function() {
  var input = document.getElementById('message');
  conn.send(input.value);
  input.value = '';
});

PHP WebSocket Server

// 创建WebSocket服务器
$server = new \WebSocket\Server("0.0.0.0", 8080);

// 当有新连接时
$server->on('open', function (\WebSocket\Connection $connection) {
  // 处理连接建立的代码
});

// 当有新消息时
$server->on('message', function (\WebSocket\Connection $connection, $msg) {
  // 处理消息的代码
});

// 当连接关闭时
$server->on('close', function (\WebSocket\Connection $connection) {
  // 处理连接关闭的代码
});

$server->run();

Message Sending and Receiving

// 前端 AJAX 轮询获取消息
function getMessages() {
  var req = new XMLHttpRequest();
  req.onreadystatechange = function() {
    if (req.readyState == XMLHttpRequest.DONE) {
      var messages = document.getElementById('messages');
      messages.innerHTML = req.responseText;
      messages.scrollTop = messages.scrollHeight - messages.clientHeight;
    }
  };
  req.open('GET', 'get_messages.php', true);
  req.send();
}
setInterval(getMessages, 3000);
// get_messages.php 示例
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  $messages = $db->getMessages();
  foreach ($messages as $message) {
    echo "{$message['username']}: {$message['message']}<br />";
  }
}

Database Interaction

// PDO 连接 MySQL
$db = new PDO("mysql:host=localhost;dbname=chat;charset=utf8", "root", "");

// 插入消息
$stmt = $db->prepare("INSERT INTO messages (username, message) VALUES (?, ?)");
$stmt->execute([$username, $message]);

// 获取最近 50 条消息
$stmt = $db->prepare("SELECT * FROM messages ORDER BY id DESC LIMIT 50");
$stmt->execute();
$messages = $stmt->fetchAll();

Conclusion

The code snippets provide a functional prototype of a real-time chat system; however, production deployments should incorporate security measures, error handling, and scalability improvements to ensure reliability.

MySQLWebSocketphpajaxReal-time Chat
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.