7

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.

HectorLector
  • 1,851
  • 1
  • 23
  • 33
  • 2
    Do you have access to the external server to check for changes there? Maybe that API asks for HTTP/2 and cURL silently uses that? – Nico Haase Sep 25 '20 at 07:46
  • @NicoHaase I do not have access to the external server. I just have their public docs and they did not change: https://docs.digistore24.com/knowledge-base/api-basics/?lang=en – HectorLector Sep 25 '20 at 07:49
  • in `file_get_contents` the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter. This might be why the endpoint server might've set a 426 response. – PatricNox Sep 25 '20 at 07:55

1 Answers1

2

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' ])
);