How to make asynchronous HTTP requests in PHP

后端 未结 18 2062
梦如初夏
梦如初夏 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 02:50

    You can use this library: https://github.com/stil/curl-easy

    It's pretty straightforward then:

    getOptions()->set(CURLOPT_RETURNTRANSFER, true);
    
    // Specify function to be called when your request is complete
    $request->addListener('complete', function (cURL\Event $event) {
        $response = $event->response;
        $httpCode = $response->getInfo(CURLINFO_HTTP_CODE);
        $html = $response->getContent();
        echo "\nDone.\n";
    });
    
    // Loop below will run as long as request is processed
    $timeStart = microtime(true);
    while ($request->socketPerform()) {
        printf("Running time: %dms    \r", (microtime(true) - $timeStart)*1000);
        // Here you can do anything else, while your request is in progress
    }
    

    Below you can see console output of above example. It will display simple live clock indicating how much time request is running:


    animation

提交回复
热议问题