Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make HTTP/1.1 request with PHP

Tags:

http

php

My code is using file_get_contents() to make GET requests to an API endpoint. It looks like it is using HTTP/1.0 and my sysadmin says I need to use HTTP/1.1. How can I make an HTTP/1.1 request? Do I need to use curl or is there a better/easier way?

Update

I decided to use cURL since I am using PHP 5.1.6. I ended up forcing HTTP/1.1 by doing this:

curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

If I was using 5.3 or later I would have tried doing something like this:

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

http://us.php.net/manual/en/context.http.php

Note: PHP prior to 5.3.0 does not implement chunked transfer decoding. If this value is set to 1.1 it is your responsibility to be 1.1 compliant.

Another option I found which might provide HTTP/1.1 is to use the HTTP extension

like image 900
ejunker Avatar asked Apr 21 '10 16:04

ejunker


2 Answers

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.

like image 57
Jonatan Littke Avatar answered Sep 27 '22 19:09

Jonatan Littke


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);
like image 26
Charles Henry Avatar answered Sep 27 '22 18:09

Charles Henry