W3docs

How do I implement basic "Long Polling"?

Here's an example of how you can implement Long Polling in PHP:

Here's an example of how you can implement Long Polling in PHP:

How to implement Long Polling in PHP?

<?php

// Prevent PHP execution timeout during long waits
set_time_limit(0);

// Define a function to simulate getting new data
function getNewData()
{
  // Simulate data arriving after a few checks
  static $checkCount = 0;
  $checkCount++;
  if ($checkCount > 5) {
    return "New data is available!";
  }
  return null;
}

// Set maximum time the server should keep the connection open
$maxWaitTime = 30; // seconds
$startTime = time();

// Keep the connection open until new data is available or the maximum wait time is reached
while (true) {
  // Check for new data
  $newData = getNewData();
  if ($newData) {
    // Send new data to the client
    echo $newData;
    // Flush output buffers to ensure data is sent immediately
    ob_flush();
    flush();
    break;
  }

  // Check if the maximum wait time has been reached
  $waitTime = time() - $startTime;
  if ($waitTime >= $maxWaitTime) {
    break;
  }

  // Sleep for a short period of time before checking for new data again
  usleep(100000); // 100ms
}
?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This PHP script keeps the connection open until new data is available or the maximum wait time is reached. The set_time_limit(0) prevents execution timeouts, while ob_flush() and flush() ensure the client receives the data immediately. The client initiates the request, handles the response, and then immediately sends a new request to maintain the long polling cycle:

function longPoll() {
  fetch('long_polling.php')
    .then(response => response.text())
    .then(data => {
      console.log('Received:', data);
      // Handle the new data here
      // Immediately initiate the next request to maintain the cycle
      longPoll();
    })
    .catch(error => {
      console.error('Polling failed:', error);
      // Retry after a delay on error
      setTimeout(longPoll, 5000);
    });
}

// Start the long polling cycle
longPoll();

You can use this technique to create a real-time chat application, real-time notifications system, or any other type of web application that requires real-time behavior.

It's important to note that Long Polling can put a lot of strain on the server, as it requires the server to keep connections open for potentially long periods of time. If you expect your application to have a high volume of traffic, you may want to consider using a more efficient technique such as WebSockets or Server-Sent Events.