Monday, December 30, 2024

Real-time Chat Application using PHP and AJAX

This is a simple real-time chat application built using PHP and AJAX polling. It avoids using WebSocket or any other complex protocols, relying instead on basic HTTP requests (AJAX) to fetch and send messages.

Overview
Backend: PHP handles incoming messages and stores them in sessions.
Frontend: AJAX is used to send and fetch messages without reloading the page.
No Database: All messages are stored temporarily in PHP sessions.
Steps to Set Up
1. Install Required Environment
Make sure you have PHP 8.4 and Nginx installed. You can install them using the following commands:

sudo apt update
sudo apt install nginx php8.4-fpm php8.4-cli php8.4-mbstring

2. Create the PHP Chat Application
Create a folder for your chat application in the web directory (e.g., /var/www/html/chat_app), and create the following files:

a. index.php (Main Chat Interface)

<?php
session_start();

// Initialize session messages if not set
if (!isset($_SESSION['messages'])) {
    $_SESSION['messages'] = [];
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat App</title>
    <style>
        #chat-box {
            width: 400px;
            height: 300px;
            border: 1px solid #ccc;
            overflow-y: scroll;
            padding: 10px;
        }
        #message {
            width: 300px;
            padding: 5px;
        }
    </style>
</head>
<body>
    <h1>PHP Chat App</h1>
    <div id="chat-box">
        <?php
        // Display all messages
        foreach ($_SESSION['messages'] as $message) {
            echo "<p><strong>{$message['user']}:</strong> {$message['message']}</p>";
        }
        ?>
    </div>
    <input type="text" id="message" placeholder="Enter your message..." />
    <button onclick="sendMessage()">Send</button>

    <script>
        // Send message using AJAX
        function sendMessage() {
            var message = document.getElementById("message").value;
            if (message.trim() === '') return;

            // Send message to server
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'send_message.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status == 200) {
                    // Clear input and refresh chat
                    document.getElementById("message").value = '';
                    fetchMessages();
                }
            };
            xhr.send('message=' + encodeURIComponent(message));
        }

        // Fetch new messages every 2 seconds
        function fetchMessages() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'get_messages.php', true);
            xhr.onload = function() {
                if (xhr.status == 200) {
                    document.getElementById('chat-box').innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }

        // Poll for new messages every 2 seconds
        setInterval(fetchMessages, 2000);
    </script>
</body>
</html>

index.php serves as the main chat interface where users can type messages, and those messages are sent using AJAX to the send_message.php script.
It also periodically fetches new messages from the server every 2 seconds via the fetchMessages() function.
b. send_message.php (Handle Sending Messages)

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message'])) {
    $message = $_POST['message'];
    $user = 'User ' . rand(1, 1000); // Random user for demo

    // Save the message in session
    $_SESSION['messages'][] = ['user' => $user, 'message' => $message];

    // Return a success response
    echo 'Message sent';
}
?>

send_message.php receives POST requests containing messages and stores them in PHP sessions.
c. get_messages.php (Fetch Messages)

<?php
session_start();

// Display all messages from session
if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $message) {
        echo "<p><strong>{$message['user']}:</strong> {$message['message']}</p>";
    }
}
?>

get_messages.php returns all stored messages from the session. The client will periodically make requests to this script to display the latest messages.
3. Configure Nginx
You need to configure Nginx to serve your PHP files correctly.

1.Edit the Nginx configuration file:

sudo nano /etc/nginx/sites-available/default

2.Update the configuration to look like this:

server {
    listen 80;
    server_name your-domain.com;

    root /var/www/html/chat_app;  # Update with your chat app directory path

    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ .php$ {
        fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

3.Restart Nginx to apply the changes:

sudo systemctl restart nginx

4. Test the Chat Application
Now, you can access your chat application by visiting:

http://your-domain.com

You should see a simple chat interface. After entering a message and clicking the “Send” button, the message will be displayed in the chat box, and the page will automatically update every 2 seconds to show new messages.

Summary
This setup uses AJAX polling to simulate real-time chat without relying on WebSocket or other complex protocols. Every 2 seconds, the client sends a request to the server to fetch new messages. This is a simple solution ideal for small-scale chat applications and doesn’t require a database; all data is stored temporarily in PHP sessions.

If you need to scale the application, consider integrating a database to store messages persistently.

Add comment

Fill out the form below to add your own comments