How to make asynchronous HTTP requests in PHP

后端 未结 18 2043
梦如初夏
梦如初夏 2020-11-22 02:13

Is there a way in PHP to make asynchronous HTTP calls? I don\'t care about the response, I just want to do something like file_get_contents(), but not wait for

18条回答
  •  别跟我提以往
    2020-11-22 03:04

    If you control the target that you want to call asynchronously (e.g. your own "longtask.php"), you can close the connection from that end, and both scripts will run in parallel. It works like this:

    1. quick.php opens longtask.php via cURL (no magic here)
    2. longtask.php closes the connection and continues (magic!)
    3. cURL returns to quick.php when the connection is closed
    4. Both tasks continue in parallel

    I have tried this, and it works just fine. But quick.php won't know anything about how longtask.php is doing, unless you create some means of communication between the processes.

    Try this code in longtask.php, before you do anything else. It will close the connection, but still continue to run (and suppress any output):

    while(ob_get_level()) ob_end_clean();
    header('Connection: close');
    ignore_user_abort();
    ob_start();
    echo('Connection Closed');
    $size = ob_get_length();
    header("Content-Length: $size");
    ob_end_flush();
    flush();
    

    The code is copied from the PHP manual's user contributed notes and somewhat improved.

提交回复
热议问题