Send HTTP request from PHP without waiting for response?

后端 未结 10 942
温柔的废话
温柔的废话 2020-12-08 00:25

I want to have an HTTP GET request sent from PHP. Example:

http://tracker.example.com?product_number=5230&price=123.52

The idea is to d

10条回答
  •  旧时难觅i
    2020-12-08 01:05

    We were using fsockopen and fwrite combo, then it up and stopped working one day. Or it was kind of intermittent. After a little research and testing, and if you have fopen wrappers enabled, I ended up using file_get_contents and stream_context_create functions with a timeout that is set to 100th of second. The timeout parameter can receive floating values (https://www.php.net/manual/en/context.http.php). I wrapped it in a try...catch block so it would fail silently. It works beautifully for our purposes. You can do logging stuff in the catch if needed. The timeout is the key if you don't want the function to block runtime.

    function fetchWithoutResponseURL( $url )
    {
    
        $context = stream_context_create([
            "http" => [
                "method"=>"GET",
                "timeout" => .01
                ]
            ]
        );
    
        try {
            file_get_contents($url, 0, $context);
        }catch( Exception $e ){
            // Fail silently
        }
    }
    

提交回复
热议问题