How to make asynchronous HTTP requests in PHP

后端 未结 18 2042
梦如初夏
梦如初夏 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:51

    1. Fake a request abortion using CURL setting a low CURLOPT_TIMEOUT_MS

    2. set ignore_user_abort(true) to keep processing after the connection closed.

    With this method no need to implement connection handling via headers and buffer too dependent on OS, Browser and PHP version

    Master process

    function async_curl($background_process=''){
    
        //-------------get curl contents----------------
    
        $ch = curl_init($background_process);
        curl_setopt_array($ch, array(
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER =>true,
            CURLOPT_NOSIGNAL => 1, //to timeout immediately if the value is < 1000 ms
            CURLOPT_TIMEOUT_MS => 50, //The maximum number of mseconds to allow cURL functions to execute
            CURLOPT_VERBOSE => 1,
            CURLOPT_HEADER => 1
        ));
        $out = curl_exec($ch);
    
        //-------------parse curl contents----------------
    
        //$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        //$header = substr($out, 0, $header_size);
        //$body = substr($out, $header_size);
    
        curl_close($ch);
    
        return true;
    }
    
    async_curl('http://example.com/background_process_1.php');
    

    Background process

    ignore_user_abort(true);
    
    //do something...
    

    NB

    If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:

    [...]

    The solution is to disable signals using CURLOPT_NOSIGNAL

    Resources

    • curl timeout less than 1000ms always fails?

    • http://www.php.net/manual/en/function.curl-setopt.php#104597

    • http://php.net/manual/en/features.connection-handling.php

提交回复
热议问题