Developing Your Own Chat with Stranger System Using PHP

Developing Your Own Chat with Stranger System Using PHP

In today’s fast-paced digital world, the need for instant and anonymous communication has become more relevant than ever. Whether it’s to pass time, engage in a stimulating conversation, or simply connect with someone from another part of the world, chatting with strangers offers a unique opportunity. If you’re a developer looking to build a system that allows users to chat with random strangers, then you’re in the right place. In this article, we’ll explore how to create your own “Chat with Strangers” system using PHP.

Follow this video for complete guidance:

https://www.youtube.com/watch?v=6WdajogKyPE

Chat with Stranger : Full Source Code

<?php
session_start();

if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');
    
    $usersFile = 'data/users.txt';
    $chatFile = 'data/chats.txt';
    
    if (!file_exists($usersFile)) file_put_contents($usersFile, '{}');
    if (!file_exists($chatFile)) file_put_contents($chatFile, '{}');
    
    $fp = fopen($usersFile, 'c+');
    flock($fp, LOCK_EX);
    
    $users = json_decode(file_get_contents($usersFile), true) ?? [];
    $chats = json_decode(file_get_contents($chatFile), true) ?? [];
    $userId = session_id();
    
    // Clean up inactive users
    foreach ($users as $id => $user) {
        if (time() - $user['time'] > 60) {
            unset($users[$id], $chats[$user['paired'] ?? '']);
        }
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        $response = ['status' => 'error'];
        
        switch ($data['action']) {
            case 'join':
                $users[$userId] = ['paired' => false, 'time' => time()];
                foreach ($users as $id => &$user) {
                    if ($id !== $userId && $user['paired'] === false) {
                        $roomId = uniqid();
                        $user['paired'] = $users[$userId]['paired'] = $roomId;
                        $chats[$roomId] = [];
                        break;
                    }
                }
                $response = ['status' => 'success', 'paired' => $users[$userId]['paired']];
                break;
                
            case 'check':
                if (isset($users[$userId])) {
                    $users[$userId]['time'] = time();
                }
                $response = ['paired' => $users[$userId]['paired'] ?? false];
                break;
                
            case 'send':
                $roomId = $users[$userId]['paired'] ?? false;
                if ($roomId && isset($chats[$roomId])) {
                    $chats[$roomId][] = [
                        'user' => $userId,
                        'message' => htmlspecialchars($data['message']),
                        'time' => date('H:i')
                    ];
                    $response = ['status' => 'success'];
                }
                break;
                
            case 'get':
                $roomId = $users[$userId]['paired'] ?? false;
                $response = [
                    'messages' => $roomId ? ($chats[$roomId] ?? []) : [],
                    'paired' => $roomId !== false
                ];
                break;
        }
        
        file_put_contents($usersFile, json_encode($users));
        file_put_contents($chatFile, json_encode($chats));
        flock($fp, LOCK_UN);
        fclose($fp);
        echo json_encode($response);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat with Stranger</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="bg-light">
    <div class="container py-4">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Chat with Stranger</h5>
                        <span id="status" class="badge bg-warning">Connecting...</span>
                    </div>
                    <div class="card-body">
                        <div id="waiting" class="text-center">
                            <div class="spinner-border text-primary"></div>
                            <p class="mt-2">Waiting for someone to join...</p>
                        </div>
                        <div id="chat" class="d-none">
                            <div id="messages" class="border rounded p-2 mb-3" style="height: 300px; overflow-y: auto"></div>
                            <div class="input-group">
                                <input type="text" id="messageInput" class="form-control" placeholder="Type a message...">
                                <button class="btn btn-primary" id="sendBtn">Send</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    $(document).ready(function() {
        let isPaired = false;
        let lastMessageCount = 0;
        
        function updateUI(isPaired) {
            $('#waiting').toggleClass('d-none', isPaired);
            $('#chat').toggleClass('d-none', !isPaired);
            $('#status')
                .removeClass('bg-warning bg-success')
                .addClass(isPaired ? 'bg-success' : 'bg-warning')
                .text(isPaired ? 'Connected' : 'Connecting...');
        }

        function updateMessages(messages) {
            if (messages.length > lastMessageCount) {
                const currentUserId = '<?php echo session_id(); ?>';
                const html = messages.map(msg => `
                    <div class="mb-2 ${msg.user === currentUserId ? 'text-end' : ''}">
                        <small class="text-muted">${msg.time}</small>
                        <div class="d-inline-block p-2 rounded ${msg.user === currentUserId ? 
                            'bg-primary text-white' : 'bg-light border'}">${msg.message}</div>
                    </div>
                `).join('');
                
                $('#messages').html(html).scrollTop($('#messages')[0].scrollHeight);
                lastMessageCount = messages.length;
            }
        }

        function makeRequest(action, data = {}) {
            return $.ajax({
                url: '',
                method: 'POST',
                headers: {'X-Requested-With': 'XMLHttpRequest'},
                contentType: 'application/json',
                data: JSON.stringify({ action, ...data })
            });
        }

        function checkPairing() {
            makeRequest('check').done(data => {
                if (data.paired && !isPaired) {
                    isPaired = true;
                    updateUI(true);
                    clearInterval(window.checkInterval);
                    pollMessages();
                }
            });
        }

        function pollMessages() {
            if (!isPaired) return;
            makeRequest('get').done(data => {
                if (!data.paired && isPaired) {
                    alert('Other user disconnected');
                    location.reload();
                    return;
                }
                updateMessages(data.messages);
                setTimeout(pollMessages, 1000);
            });
        }

        // Event handlers
        $('#sendBtn, #messageInput').on('click keypress', function(e) {
            if ((e.type === 'click' || e.which === 13) && isPaired) {
                const $input = $('#messageInput');
                const message = $input.val().trim();
                if (message) {
                    makeRequest('send', { message });
                    $input.val('');
                }
            }
        });

        // Initialize chat
        makeRequest('join').done(data => {
            if (data.paired) {
                isPaired = true;
                updateUI(true);
                pollMessages();
            } else {
                window.checkInterval = setInterval(checkPairing, 2000);
            }
        });
    });
    </script>
</body>
</html>

Overview of Chat with Strangers System

The concept of the system is simple: users enter the platform, and the system pairs them with another user for a one-on-one chat. If no one is available for pairing, users are placed in a queue until someone else joins. This system ensures anonymity, as users don’t need to create an account or provide any personal information to start chatting.

System Requirements

Before jumping into the development, it’s important to identify the key components of the system:

  • User Pairing Logic: The core of the system is the ability to randomly pair users who enter the chat. This logic ensures that users are connected with someone in real-time.
  • Message Handling: The chat system must be able to handle real-time message exchanges, ensuring that users receive and send messages without any delays.
  • Session Management: Since users don’t need to log in, PHP sessions are used to track user connections and ensure that each user is paired correctly.
  • Data Persistence: A simple file-based storage system can be used to store users and chat messages.

Setting Up PHP

The first step in developing this system is to ensure that you have a working PHP environment with basic session handling. You’ll also need to handle file operations to store user data and chat logs. This is achieved through PHP’s session_start() function, which manages the session state for each user.

The application will consist of a PHP backend and a frontend built with HTML, CSS, and JavaScript to create a dynamic and interactive user interface.

Key Features of the Chat System

  • User Join and Pairing: When a user joins the chat, they are either paired with an available user or placed in a queue until another user joins. This is achieved by storing user data in a file, which is updated every time a user joins or leaves.
  • Real-time Messaging: Once two users are paired, they can send messages to each other in real-time. The system uses AJAX to update the chat window without requiring a page reload. Messages are stored in a chat log, which is updated whenever a new message is sent.
  • User Disconnection Handling: If a user leaves or disconnects unexpectedly, the system ensures that the other user is notified and can reconnect with a new partner. This feature helps maintain an uninterrupted chat experience.
  • Chat Interface: The chat interface is simple and easy to use. It includes a message input box, a send button, and a display area for the chat history. The layout is responsive, ensuring that it works well on both desktop and mobile devices.

Frontend Implementation

The frontend of the system is designed using HTML, CSS, and Bootstrap to provide a clean and user-friendly interface. The user is presented with a simple page that informs them when they are waiting for another user to join. Once paired, the chat interface is displayed, showing the chat history and an input field for new messages.

Backend Logic

The backend PHP script handles various actions:

  • Join Action: When a user joins, the backend checks for an available user to pair them with. If no one is available, the user is added to a waiting list.
  • Send Message: Once paired, users can send messages to each other. The message is saved to a chat log and displayed in real-time.
  • Check Pairing: The system constantly checks if the user is paired with another user. If a pairing is established, the chat window is updated accordingly.
  • Get Messages: The system retrieves the latest messages from the chat room to display them in the chat window.

Real-time Communication with AJAX

To achieve a seamless user experience, we use AJAX to handle the real-time communication between the client and the server. Whenever a user sends a message, the frontend sends an AJAX request to the server, which updates the chat log and sends a response back. This allows users to send and receive messages without refreshing the page.

Security Considerations

While this system is designed for simplicity, there are a few security concerns to consider:

  • XSS Protection: It’s crucial to sanitize user input to prevent cross-site scripting (XSS) attacks. In the provided system, the htmlspecialchars function is used to ensure that messages are properly escaped.
  • Session Hijacking: Ensure that sessions are handled securely to prevent session hijacking. Using session_regenerate_id() periodically can help mitigate this risk.

Extending the System

Once the basic functionality is in place, you can extend the system in several ways:

  • User Profiles: You could allow users to create basic profiles with usernames or avatars for a more personalized experience.
  • Voice and Video Chat: For a more interactive experience, you could integrate voice or video chat capabilities using WebRTC.
  • Moderation Features: Implement reporting and blocking features to help manage inappropriate content and behavior.

Creating a chat with strangers system using PHP is a great way to learn about real-time web applications, session management, and AJAX integration. By building this system, you’ll gain hands-on experience with handling user data, managing chat logs, and providing an engaging user experience. Whether you’re looking to build a simple chat platform or extend it with advanced features, this project offers a solid foundation to get started. Happy coding!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *