Current Location: Home> Latest Articles> Comprehensive Case Study: Real-Time Message Push in PHP Using Long Polling

Comprehensive Case Study: Real-Time Message Push in PHP Using Long Polling

gitbox 2025-08-05

Case Background

Real-time message push is essential for enhancing user interaction in web applications. It allows servers to send updates to the client instantly, improving responsiveness. While WebSocket is commonly used for this purpose, PHP combined with long polling remains a viable alternative, especially when WebSocket is not supported on the server.

Principle of Real-Time Push

The core concept behind real-time push is to maintain a persistent connection between the client and server. Unlike standard HTTP request/response cycles, long polling allows the server to delay its response until new data is available, thereby mimicking a real-time experience.

How Long Polling Works

The long polling mechanism functions as follows:

  • The client sends a request to the server.
  • The server checks if there are new messages available.
  • If a new message exists, it immediately responds with the data.
  • If no message is found, the server holds the request open for a set time or until new data is generated.
  • Once a message is available or the timeout is reached, the server responds.
  • The client then repeats the request, creating a loop.

Implementation Steps

Create a Database Table

Start by creating a database table to store messages. Below is an example schema for a table named messages:


CREATE TABLE messages (
  id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  content VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Frontend Page Development

The frontend displays messages received from the server. Here’s a basic HTML layout with jQuery included:


<!DOCTYPE html>
<html>
<head>
  <title>Real-Time Message Push</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="app.js"></script>
</head>
<body>
  <div id="messages"></div>
</body>
</html>

Backend Logic with PHP

The PHP backend handles the polling logic and data retrieval. Create a file called index.php to manage the client’s request.

Basic PHP Example


<?php
// Database connection
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$lastId = isset($_GET['last_id']) ? intval($_GET['last_id']) : 0;
$timeout = 30;
$startTime = time();

while (true) {
    $sql = "SELECT * FROM messages WHERE id > $lastId ORDER BY id ASC";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $messages = [];
        while($row = $result->fetch_assoc()) {
            $messages[] = $row;
        }
        echo json_encode(["status" => "success", "data" => $messages]);
        break;
    } else {
        sleep(1);
    }

    if ((time() - $startTime) > $timeout) {
        echo json_encode(["status" => "timeout", "data" => []]);
        break;
    }
}
$conn->close();
?>

JavaScript Polling Logic (app.js)


let lastId = 0;
function fetchMessages() {
  $.ajax({
    url: 'index.php',
    type: 'GET',
    data: { last_id: lastId },
    success: function(response) {
      if (response.status === 'success') {
        response.data.forEach(function(msg) {
          $('#messages').append('<p>' + msg.content + '</p>');
          lastId = msg.id;
        });
      }
      fetchMessages();
    },
    error: function() {
      setTimeout(fetchMessages, 3000);
    }
  });
}

$(document).ready(function() {
  fetchMessages();
});

Conclusion

By leveraging PHP and long polling, we successfully built a basic real-time message push system. This approach is especially useful in environments where WebSocket support is limited. It's ideal for notification systems, support chats, or other scenarios where timely information delivery is required, without needing complex server setups.