Question

Taking a long polling request, if the server does not respond after a certain period an unpleasant error is returned (405 with nginx). How to expire the request with PHP after certain seconds? How many seconds you recommend? Thanks you in advance.

Was it helpful?

Solution

Ok then here's how i would do it , I already built a similar script for one of my spare time projects, instead of doing a full infinite loop, i would do a loop with a limited number of loops, and a sleep in the middle to save the extensive cpu usage, might not exactly how your code is designed but it's good, and it stops gracefully with a normal 200 code, of course you can change the loop counter and the sleep value to suit your code.

<?php
    header('Cache-Control: no-cache');
    header("Content-Type: text/event-stream");
    $i = 60;
    while($i--){
        echo "data: ".date("Y-m-d H:i:s")."\n\n";
        echo "\n\n";
        ob_flush();
        flush();
        sleep(1);
    }

Then leave it for the javascript to reconnect and start a new loop.

PS: Do you actually get your data to stream? or does the stream stay blank till the connection is terminated?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top