Home  >  Article  >  Backend Development  >  Application analysis of PHP real-time communication function in social network applications

Application analysis of PHP real-time communication function in social network applications

PHPz
PHPzOriginal
2023-08-10 20:09:091251browse

Application analysis of PHP real-time communication function in social network applications

Analysis of the application of PHP real-time communication function in social network applications

With the rapid development of social network applications, users’ demand for real-time communication and real-time updates is also increasing. Come higher and higher. The traditional way of refreshing web pages can no longer meet user requirements. Therefore, real-time communication functions are becoming more and more important in social network applications. As a language widely used in Web development, PHP has gradually developed corresponding real-time communication solutions.

This article will use a simple chat application to demonstrate how to use PHP to implement real-time communication functions.

Preparation work

Before you start writing code, you need to install the following software or libraries:

  • PHP (you can use a packaged development environment such as xampp or wampp)
  • Composer (PHP Package Manager)

You also need to create a database to store chat records. You can use the following SQL statement to create a table:

CREATE TABLE messages (
  id INT(11) AUTO_INCREMENT PRIMARY KEY,
  sender VARCHAR(50) NOT NULL,
  receiver VARCHAR(50) NOT NULL,
  message TEXT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Front-end code

First, we need a front-end interface to display chat records and update messages in real time. In this example, we use HTML, CSS, and JavaScript to create a simple chat interface. Here is the sample code:

<!DOCTYPE html>
<html>
<head>
    <title>实时聊天</title>
    <style>
        #message-box {
            border: 1px solid black;
            height: 200px;
            width: 300px;
            overflow: scroll;
        }
    </style>
</head>
<body>
    <div id="message-box"></div>
    <input type="text" id="message-input" placeholder="输入消息">
    <button id="send-button">发送</button>

    <script>
        const messageBox = document.getElementById("message-box");
        const messageInput = document.getElementById("message-input");
        const sendButton = document.getElementById("send-button");

        // 更新消息
        function updateMessages() {
            fetch("get_messages.php")
                .then(response => response.json())
                .then(data => {
                    messageBox.innerHTML = "";
                    data.forEach(message => {
                        const messageElement = document.createElement("div");
                        messageElement.innerHTML = `${message.sender}: ${message.message}`;
                        messageBox.appendChild(messageElement);
                    });
                });
        }

        // 发送消息
        function sendMessage() {
            const message = messageInput.value;
            if (message !== "") {
                fetch("send_message.php", {
                    method: "POST",
                    body: JSON.stringify({ message }),
                    headers: {
                        "Content-type": "application/json"
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            updateMessages();
                            messageInput.value = "";
                        }
                    });
            }
        }

        updateMessages();

        sendButton.addEventListener("click", sendMessage);
    </script>
</body>
</html>

Backend code

We use PHP and MySQL to handle the backend logic. The following is the code for the get_messages.php file, used to get the chat history:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chat_app";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("连接失败:" . $conn->connect_error);
}

$sql = "SELECT * FROM messages";
$result = $conn->query($sql);

$messages = [];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }
}

header("Content-type: application/json");
echo json_encode($messages);

$conn->close();
?>

The following is the code for the send_message.php file, used to send the message:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chat_app";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("连接失败:" . $conn->connect_error);
}

$data = json_decode(file_get_contents("php://input"), true);

$message = $data["message"];

$sql = "INSERT INTO messages (sender, receiver, message) VALUES ('User A', 'User B', '$message')";

if ($conn->query($sql) === true) {
    $response = [
        "success" => true
    ];
} else {
    $response = [
        "success" => false
    ];
}

header("Content-type: application/json");
echo json_encode($response);

$conn->close();
?>

Run the example

First, save the front-end code as an HTML file, such as chat.html. Then, go to the directory where the HTML file is located on the command line and run the following command to install the necessary dependencies:

composer require pusher/pusher-php-server

Then, create a file named config.php to store Pusher’s configuration information :

<?php
require __DIR__ . '/vendor/autoload.php';

$options = array(
    'cluster' => 'YOUR_PUSHER_CLUSTER',
    'encrypted' => true
);

$pusher = new PusherPusher(
    'YOUR_PUSHER_APP_KEY',
    'YOUR_PUSHER_APP_SECRET',
    'YOUR_PUSHER_APP_ID',
    $options
);
?>

Replace YOUR_PUSHER_CLUSTER, YOUR_PUSHER_APP_KEY, YOUR_PUSHER_APP_SECRET and YOUR_PUSHER_APP_ID with the relevant information of your Pusher application.

Finally, run the following command in the command line to start the built-in PHP server:

php -S localhost:8000

Visit http://localhost:8000/chat.html in the browser to see the chat interface . You can open multiple instances in different browser windows or tabs and chat live.

Summary

Through the examples in this article, we can see that it is not complicated to use PHP to implement real-time communication functions. With the help of existing libraries and technologies, we can provide a better user experience and meet users' real-time needs for social network applications. Of course, the example in this article is just a simple chat application. The actual situation may be more complex and require more functions and security measures. But I hope this article can provide you with some basic ideas and methods for realizing real-time communication functions.

The above is the detailed content of Application analysis of PHP real-time communication function in social network applications. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn