As people become more and more dependent on the Internet, real-time online chat rooms have become a standard feature of many websites. This article will introduce how to use PHP to implement a basic real-time online chat room.
Before you start, make sure your environment has the following conditions:
First, create a MySQL database and a table to save chat records. Execute the following command:
CREATE DATABASE chat; USE chat; CREATE TABLE messages ( id INT(11) AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, message TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP );
The above command will create a database named "chat" and a table named "messages" in it to store chat records. The table contains 4 fields, namely "id", "username", "message" and "created_at". Among them, "id" is the automatically incremented primary key, "username" is the user name of the sender, "message" is the message content, and "created_at" is the message sending time.
Next, create the HTML file chat.html and the CSS file chat.css. Only the key codes of HTML and CSS are shown here:
chat.html
<!DOCTYPE html> <html> <head> <title>Online Chat Room</title> <link rel="stylesheet" type="text/css" href="chat.css"> </head> <body> <div class="chat-container"> <div class="chat-header"> <h2>Chat Room</h2> </div> <div class="chat-messages"></div> <div class="chat-form"> <form> <input type="text" name="username" placeholder="Username" required> <input type="text" name="message" placeholder="Type your message here" required> <button type="submit">Send</button> </form> </div> </div> <script src="jquery.min.js"></script> <script src="chat.js"></script> </body> </html>
chat.css
body { margin: 0; padding: 0; font-family: Arial, sans-serif; } .chat-container { width: 80%; margin: 50px auto; border: 1px solid #ccc; box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.1); } .chat-header { padding: 10px; background-color: #eee; } .chat-header h2 { margin: 0; font-size: 18px; } .chat-messages { height: 300px; overflow: auto; padding: 10px; } .chat-form { padding: 10px; } .chat-form form { display: flex; flex-wrap: wrap; } .chat-form input { flex: 1; margin: 0 5px 0 0; padding: 10px; border: none; border-radius: 3px; } .chat-form button { flex-basis: 100px; padding: 10px; background-color: #0099ff; color: #fff; border: none; border-radius: 3px; cursor: pointer; transition: background-color 0.2s; } .chat-form button:hover { background-color: #0088cc; }
A basic chat room page is created here, including a chat record area, a messaging form, and other related elements.
Finally, use PHP to write backend code to implement real-time communication functions. Create a file named chat.php which contains the following code:
<?php /* 设置响应格式为JSON */ header('Content-Type: application/json'); /* 连接数据库 */ define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASSWORD', '123456'); define('DB_NAME', 'chat'); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); /* 检查数据库连接是否成功 */ if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } /* 处理消息发送请求 */ if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $message = $_POST['message']; $sql = "INSERT INTO messages (username, message) VALUES ('$username', '$message')"; if (mysqli_query($conn, $sql)) { echo json_encode(['status' => 'success']); } else { echo json_encode(['status' => 'error', 'message' => mysqli_error($conn)]); } } else { /* 处理消息获取请求 */ $last_id = $_GET['last_id']; $sql = "SELECT * FROM messages WHERE id > $last_id ORDER BY created_at ASC"; $result = mysqli_query($conn, $sql); $messages = []; while ($row = mysqli_fetch_assoc($result)) { $messages[] = $row; } echo json_encode(['status' => 'success', 'messages' => $messages]); } mysqli_close($conn);
The above code contains the following three parts:
Finally, write the JavaScript code in chat.js to handle the real-time communication on the page. In this example, we will use jQuery to simplify the code and handle AJAX requests. The following is the core part of the chat.js file:
$(function() { /* 存储最后一条消息的ID */ var last_id = 0; /* 获取所有消息 */ function getMessages() { $.get('chat.php', {'last_id': last_id}, function(data) { if (data.status == 'success') { /* 迭代所有消息并添加到聊天室中 */ $.each(data.messages, function(index, message) { var html = '<p><strong>' + message.username + ':</strong> ' + message.message + '</p>'; $('.chat-messages').append(html); /* 更新最后一条消息的ID */ last_id = message.id; }); /* 滚动到底部以显示最新的消息 */ $('.chat-messages').scrollTop($('.chat-messages')[0].scrollHeight); } }, 'json'); } /* 获取所有消息 */ getMessages(); /* 处理消息发送表单的提交事件 */ $('.chat-form form').submit(function(e) { e.preventDefault(); /* 获取表单输入 */ var username = $('input[name="username"]').val(); var message = $('input[name="message"]').val(); /* 发送AJAX请求 */ $.post('chat.php', {'username': username, 'message': message}, function(data) { if (data.status == 'success') { /* 清空输入框 */ $('input[name="message"]').val(''); } else { /* 处理错误 */ alert('Error: ' + data.message); } }, 'json'); }); /* 每5秒获取一次消息 */ setInterval(getMessages, 5000); });
The above code uses jQuery and AJAX to complete the following tasks:
Now, everything is ready. Open the chat.html file and enter your username and a message, then click the "Send" button. If everything is fine, you should see all of your previously sent messages as well as the one you just sent. Congratulations, you have successfully created a real-time online chat room!
Conclusion
In this article, we introduced how to create a real-time online chat room using PHP and AJAX. Although this chat room is relatively simple, based on this, you can try to improve it yourself and add more features, such as private messages, emoticons, and more. I hope you can develop more practical web applications based on this.
The above is the detailed content of How to implement an online chat room using PHP. For more information, please follow other related articles on the PHP Chinese website!