Make HTTP/1.1 request with PHP

I'd use cURL in either case, it gives you more control and in particular it gives you the timeout option. That's very important when calling an external API so as not to allow your application to freeze whenever a remote API is down.

Could like this:

# Connect to the Web API using cURL.
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.url.com/api.php?123=456'); 
curl_setopt($ch, CURLOPT_TIMEOUT, '3'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$xmlstr = curl_exec($ch); 
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

cURL will use HTTP/1.1 per default, unless you specify something else using curl_setopt($s,CURLOPT_HTTPHEADER,$headers);, where $headers is an array.


Just so others who want to use stream_context_create/file_get_contents know, if your server is configured to use keep-alive connections, the response will not return anything, you need to add 'protocol_version' => 1.1 as well as 'header' => 'Connection: close'.

Example below:

$ctx = stream_context_create(array(
               'http' => array(
                  'timeout' => 5,
                  'protocol_version' => 1.1,
                  'header' => 'Connection: close'
                )
              ));
$res = file_get_contents($url, 0, $ctx);

Tags:

Php

Http