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.
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.
The long polling mechanism functions as follows:
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
);
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>
The PHP backend handles the polling logic and data retrieval. Create a file called index.php to manage the client’s request.
<?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();
?>
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();
});
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.