Current Location: Home> Latest Articles> 【Complete Guide to Building Real-Time Chat and Virtual Currency System with PHP】

【Complete Guide to Building Real-Time Chat and Virtual Currency System with PHP】

gitbox 2025-06-06

Building Real-Time Chat and Virtual Currency Management with PHP

Real-time chat has become an essential feature in many modern web applications. From social platforms and customer support to live streaming and community tools, real-time messaging enhances user engagement significantly. Alongside this, a virtual currency system enables monetization through user top-ups and in-app transactions. This guide walks you through building such a system using PHP and the Swoole extension.

Creating a WebSocket-Based Chat Server with PHP

WebSocket technology is the backbone of any real-time communication system. In the PHP ecosystem, Swoole offers robust support for WebSocket servers, enabling efficient and high-performance messaging between users.

Start by installing Swoole via Composer:

composer require swoole/swoole-src

Then, set up a WebSocket server in your PHP project:

$server = new swoole_websocket_server("0.0.0.0", 9501);

$server->on('open', function(swoole_websocket_server $server, $request) {
    echo "server: handshake success with fd {$request->fd}\n";
});

$server->on('message', function(swoole_websocket_server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data}, opcode:{$frame->opcode}, fin:{$frame->finish}\n";
    $server->push($frame->fd, "this is server");
});

$server->on('close', function($ser, $fd) {
    echo "client {$fd} closed\n";
});

$server->start();

On the frontend, you can use JavaScript to connect and communicate with the WebSocket server:

const options = {
    transports: ['websocket'],
};
const socket = io('http://localhost:9501', options);

socket.on('connect', () => {
    console.log('websocket connected.');
    socket.emit('hello', "hello server");
});

socket.on('message', data => {
    console.log('received:', data);
});

socket.on('disconnect', () => console.log('websocket disconnected.'));

User Top-Up and Virtual Currency Management

To support in-app purchases, tips, or premium services, a virtual currency system is necessary. This system typically includes user account management, top-up processing, balance tracking, and transaction records.

Below is a basic PHP and MySQL example demonstrating login authentication and balance retrieval:

$username = $_POST["username"];
$password = $_POST["password"];
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
mysqli_query($conn, "SET NAMES UTF8");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Welcome " . $row["username"] . "!";
        echo "Your balance is " . $row["balance"] . " units.";
    }
} else {
    echo "Invalid username or password!";
}

$conn->close();

This script handles basic login and balance display. In production, consider implementing security measures like token-based authentication, input validation, and SQL injection protection.

Conclusion

This tutorial has shown how to use PHP and Swoole to develop a real-time chat system and expand it with a virtual currency-based user recharge mechanism. This architecture is highly suitable for social platforms, live interaction apps, and content monetization websites. You can further enhance it by adding features like gifting, leveling, or a virtual goods marketplace to enrich user engagement and revenue opportunities.