Make HTTP / 1.1 Request with PHP

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

Update

I decided to use cURL as I am using PHP 5.1.6. I ended up running HTTP / 1.1 by doing the following:

 curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); 

If I were using 5.3 or later, I would try to do 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 decoding with a channel extension. If this value is set to 1.1, this responsibility should be compatible with 1.1.

Another option I found that can provide HTTP / 1.1 is to use the HTTP extension

+7
php
source share
2 answers

I would use cURL anyway, it gives you more control and, in particular, gives you a timeout parameter. This is very important when calling an external API to prevent your application from freezing when you delete a remote API.

Maybe so:

 # 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 by default, unless you specify something else using curl_setopt($s,CURLOPT_HTTPHEADER,$headers); where $ headers is an array.

+3
source

Just so that other users who want to use stream_context_create / file_get_contents know that if your server is configured to use keep-alive connections, the response will not return, 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); 
+2
source

All Articles