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¶m2=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.
The people who run the server upgraded their software.
One is using the curl library, the other some custem php-core based method.
Depends on your use case. Curl is more flexible. You should be using something like Guzzle (a http client library).
Maybe.