How to implement basic long polling with PHP?

Spread the love

Sometimes, we want to implement basic long polling with PHP.

In this article, we’ll look at how to implement basic long polling with PHP.

How to implement basic long polling with PHP?

To implement basic long polling with PHP, we create a PHP script that does nothing until something we’re looking for is returned.

Then we keep running the script.

For instance, we write

<?php
if(rand(1, 3) == 1){
    header("HTTP/1.0 404 Not Found");
    die();
}

sleep(rand(2, 10));
echo(rand(1, 10));
?>

in a file to return a 404 error and stop the script with die if we don’t get 1 from rand.

Otherwise, we call sleep to pause the script for a random number of seconds.

And then we use echo to show a random number.

Conclusion

To implement basic long polling with PHP, we create a PHP script that does nothing until something we’re looking for is returned.

Leave a Reply

Your email address will not be published.