Home > Article > Backend Development > PHP develops real-time chat system for music sharing and online playback
PHP develops real-time chat system for music sharing and online playback
With the development of the Internet, real-time chat system has become an important communication tool in people's daily lives. In order to increase the user experience, we can add music sharing and online playback functions to the chat system, so that users can enjoy music at the same time during the chat process, increasing the fun of communication. This article will introduce how to use PHP to develop the music sharing and online playback functions of the real-time chat system, and give corresponding code examples.
1. Environment preparation
Before starting development, we need to prepare the server environment for running PHP. It is recommended to use integrated development environments such as XAMPP or WAMP, which include Apache server, MySQL database and PHP interpreter to facilitate our development and testing.
2. Create a database
First, we need to create a database to store chat records and music information. Run the following SQL statements in MySQL to create the corresponding data table:
CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) NOT NULL, password VARCHAR(50) NOT NULL ); CREATE TABLE messages ( id INT PRIMARY KEY AUTO_INCREMENT, sender_id INT NOT NULL, receiver_id INT NOT NULL, content TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE music ( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100) NOT NULL, artist VARCHAR(100) NOT NULL, url VARCHAR(255) NOT NULL );
3. User login and registration
In the chat system, users need to register and log in to use the chat function. Next, we use PHP to write the code for user login and registration.
User registration page (register.php)
<!DOCTYPE html> <html> <head> <title>用户注册</title> </head> <body> <h1>用户注册</h1> <form action="register.php" method="POST"> <input type="text" name="username" placeholder="用户名" required> <br><br> <input type="password" name="password" placeholder="密码" required> <br><br> <button type="submit">注册</button> </form> </body> </html>
User registration processing (register.php)
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $password = $_POST['password']; // 将用户名和密码插入数据库中 $connection = mysqli_connect('localhost', 'root', '', 'chat_system'); $query = "INSERT INTO users (username, password) VALUES ('$username', '$password')"; mysqli_query($connection, $query); // 注册成功后跳转到登录页面 header('Location: login.php'); exit(); } ?>
4. User login and verification
User login page (login.php)
<!DOCTYPE html> <html> <head> <title>用户登录</title> </head> <body> <h1>用户登录</h1> <form action="login.php" method="POST"> <input type="text" name="username" placeholder="用户名" required> <br><br> <input type="password" name="password" placeholder="密码" required> <br><br> <button type="submit">登录</button> </form> </body> </html>
User login verification (login.php )
<?php session_start(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $password = $_POST['password']; // 根据用户名查询数据库 $connection = mysqli_connect('localhost', 'root', '', 'chat_system'); $query = "SELECT * FROM users WHERE username='$username' AND password='$password'"; $result = mysqli_query($connection, $query); // 验证用户名和密码是否正确 if (mysqli_num_rows($result) == 1) { // 登录成功后保存用户信息到session中 $user = mysqli_fetch_assoc($result); $_SESSION['user_id'] = $user['id']; $_SESSION['username'] = $user['username']; // 登录成功后跳转到聊天页面 header('Location: chat.php'); exit(); } else { echo '用户名或密码错误'; } } ?>
5. Real-time chat function
In the chat page, we use Ajax to implement the real-time chat function. When a user sends a message, we send the message to the server and store it in the database, then display the message in the chat window in real time.
Chat page (chat.php)
<?php session_start(); if (!isset($_SESSION['user_id'])) { header('Location: login.php'); exit(); } $connection = mysqli_connect('localhost', 'root', '', 'chat_system'); // 查询历史消息 $query = "SELECT * FROM messages"; $result = mysqli_query($connection, $query); $messages = mysqli_fetch_all($result, MYSQLI_ASSOC); ?> <!DOCTYPE html> <html> <head> <title>实时聊天</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h1>实时聊天</h1> <div id="chat-box"> <?php foreach ($messages as $message): ?> <p><?php echo $message['content']; ?></p> <?php endforeach; ?> </div> <form id="message-form"> <input type="text" name="message" placeholder="输入消息" required> <button type="submit">发送</button> </form> <script> // 页面加载完成后,滚动到底部 $(document).ready(function() { $('#chat-box').scrollTop($('#chat-box')[0].scrollHeight); }); // 提交消息表单 $('#message-form').submit(function(event) { event.preventDefault(); var message = $('input[name="message"]').val(); $.ajax({ url: 'send_message.php', method: 'POST', data: {message: message}, success: function() { // 清空输入框内容 $('input[name="message"]').val(''); } }); }); // 定时刷新消息 setInterval(function() { $.ajax({ url: 'get_messages.php', method: 'GET', dataType: 'json', success: function(response) { var messages = response.messages; var html = ''; // 生成消息HTML for (var i = 0; i < messages.length; i++) { html += '<p>' + messages[i].content + '</p>'; } // 更新聊天窗口内容 $('#chat-box').html(html); // 滚动到底部 $('#chat-box').scrollTop($('#chat-box')[0].scrollHeight); } }); }, 1000); </script> </body> </html>
Send message code (send_message.php)
<?php session_start(); if (!isset($_SESSION['user_id']) || $_SERVER['REQUEST_METHOD'] != 'POST') { exit(); } $sender_id = $_SESSION['user_id']; $receiver_id = 0; // 这里可以根据实际情况设置接收者的ID $content = $_POST['message']; $connection = mysqli_connect('localhost', 'root', '', 'chat_system'); $query = "INSERT INTO messages (sender_id, receiver_id, content) VALUES ($sender_id, $receiver_id, '$content')"; mysqli_query($connection, $query); ?>
Get message code (get_messages.php)
<?php $connection = mysqli_connect('localhost', 'root', '', 'chat_system'); $query = "SELECT * FROM messages"; $result = mysqli_query($connection, $query); $messages = mysqli_fetch_all($result, MYSQLI_ASSOC); echo json_encode(['messages' => $messages]); ?>
6. Music sharing and online playback
In order to realize the music sharing and online playback function, we first need to The database stores music title, artist and URL information. Users can add music and share it with other users, and other users can click links in the chat page to play the music.
Add music page (add_music.php)
<?php session_start(); if (!isset($_SESSION['user_id'])) { header('Location: login.php'); exit(); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $title = $_POST['title']; $artist = $_POST['artist']; $url = $_POST['url']; // 将音乐信息插入数据库中 $connection = mysqli_connect('localhost', 'root', '', 'chat_system'); $query = "INSERT INTO music (title, artist, url) VALUES ('$title', '$artist', '$url')"; mysqli_query($connection, $query); // 添加成功后跳转到聊天页面 header('Location: chat.php'); exit(); } ?> <!DOCTYPE html> <html> <head> <title>添加音乐</title> </head> <body> <h1>添加音乐</h1> <form action="add_music.php" method="POST"> <input type="text" name="title" placeholder="标题" required> <br><br> <input type="text" name="artist" placeholder="艺术家" required> <br><br> <input type="text" name="url" placeholder="URL" required> <br><br> <button type="submit">添加</button> </form> </body> </html>
Music play code (play_music.php)
<?php if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['id'])) { $id = $_GET['id']; // 根据ID查询音乐信息 $connection = mysqli_connect('localhost', 'root', '', 'chat_system'); $query = "SELECT * FROM music WHERE id=$id"; $result = mysqli_query($connection, $query); $music = mysqli_fetch_assoc($result); // 输出音乐信息,并自动播放 echo <<<HTML <h1>{$music['title']}</h1> <p>{$music['artist']}</p> <audio controls autoplay> <source src="{$music['url']}" type="audio/mpeg"> Your browser does not support the audio element. </audio> HTML; } else { exit(); } ?>
7. Summary
This article uses PHP to develop the music sharing and online playback functions of the real-time chat system, and shows how to achieve this function by combining database, AJAX and front-end technology. Users can share music and play online at the same time during chat, enriching the content and experience of chat. In addition to providing code examples, it also introduces the development process of related database design and user login verification. I hope this article will help you understand and implement this function.
The above is the detailed content of PHP develops real-time chat system for music sharing and online playback. For more information, please follow other related articles on the PHP Chinese website!