Send HTTP request from PHP without waiting for response?

后端 未结 10 907
温柔的废话
温柔的废话 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条回答
  • 2020-12-08 01:04
    <?php
    // Create a stream
    $opts = array(
      'http'=>array(
        'method'=>"GET",
        'header'=>"Accept-language: en" 
      )
    );
    
     $context = stream_context_create($opts);
    
    // Open the file using the HTTP headers set above
    $file = file_get_contents('http://tracker.example.com?product_number=5230&price=123.52', false, $context);
    ?>
    
    0 讨论(0)
  • 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
        }
    }
    
    0 讨论(0)
  • 2020-12-08 01:12

    I implemented function for fast GET request to url without waiting for response:

    function fast_request($url)
    {
        $parts=parse_url($url);
        $fp = fsockopen($parts['host'],isset($parts['port'])?$parts['port']:80,$errno, $errstr, 30);
        $out = "GET ".$parts['path']." HTTP/1.1\r\n";
        $out.= "Host: ".$parts['host']."\r\n";
        $out.= "Content-Length: 0"."\r\n";
        $out.= "Connection: Close\r\n\r\n";
    
        fwrite($fp, $out);
        fclose($fp);
    }
    
    0 讨论(0)
  • 2020-12-08 01:17

    You can use shell_exec, and command line curl.

    For an example, see this question

    0 讨论(0)
提交回复
热议问题