John Davidson

php - Real time updating of an indicator without polling


I have overtaken a project that uses core php and react as frontend,

In the page, it has a team indicator, basically enrolled team / max team,

Now, I wanted the team indicator to be realtime, but would like to avoid polling as it will exhaust the server.

One thing I can think of is websocket, but I have read that it's going to be obsolete, and would like to know a long term solution.

My Answer:
One possible solution for real-time updating of the team indicator without polling is to use server-sent events (SSE). SSE is a technology that allows a server to push updates to a client over a single, long-lived connection.

With SSE, the client establishes a connection to the server and the server can then push updates to the client whenever there is new data available. This eliminates the need for the client to constantly poll the server for updates.

To implement SSE in your PHP application, you can use the `EventSource` API in JavaScript on the client side to establish a connection to a PHP script on the server side that sends updates to the client.

Here is a basic example of how you can implement SSE in PHP:

1. Server-side PHP script (e.g., `sse.php`):

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$teamSize = 0; // Initial team size

while (true) {
// Get the current team size from the database or wherever it is stored
$newTeamSize = getTeamSize();

if ($newTeamSize !== $teamSize) {
echo "data: $newTeamSize\n\n";
$teamSize = $newTeamSize;

// Sleep for a short interval before checking for updates again

function getTeamSize() {
// Implement your logic to get the current team size here
return rand(1, 10); // Dummy data for demonstration purposes

2. Client-side JavaScript code:

const eventSource = new EventSource('sse.php');

eventSource.onmessage = function(event) {
const teamSize =;
// Update the team indicator on the page with the new team size
document.getElementById('team-indicator').innerText = teamSize;

In this example, the server-side PHP script continuously checks for updates to the team size and sends them to the client using SSE. The client-side JavaScript code listens for these updates and updates the team indicator on the page accordingly.

Using SSE can provide real-time updates to your team indicator without the need for constant polling and can be a more efficient and scalable solution compared to traditional polling methods.

Rate this post

3 of 5 based on 7677 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us