PHP HTTP 426 - file_get_contents vs. curl

1k Views Asked by At

I have a simple PHP script, which sends a GET request with some parameters to an external API, and receive some json data in response.

I used file_get_contents for this, and it worked for the last months.

Example:

$url = 'https://example.com?param1=xxx&param2=yyy';
$data = file_get_contents($url);

Suddenly it stopped working with the following error:

failed to open Stream: HTTP request failed!
HTTP1/1 426 Upgrade Required

I replaced it with cURL and it worked:

function curlGet($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

My questions are:

  • What can cause this behavior?
  • What is exactly the difference between the 2 methods?
  • Should I always use curl?
  • Is there a way to prevent this problem when using file_get_contents?

I do not think that anything on my server was changed. I also tested it locally and it had the same problem/solution, so I am guessing that something changed with the external server/API.

I am using PHP7.

1

There are 1 best solutions below

2
On

What can cause this behavior?

The people who run the server upgraded their software.

What is exactly the difference between the 2 methods?

One is using the curl library, the other some custem php-core based method.

Should I always use curl?

Depends on your use case. Curl is more flexible. You should be using something like Guzzle (a http client library).

Is there a way to prevent this problem when using file_get_contents?

Maybe.

$file = file_get_contents(
    'http://www.example.com/',
    false,
    stream_context_create(
        [ 'http'=> ['method'=>"GET"]],
        ['protocol_version' => '1.1' ])
);