Search code examples
phpfile-get-contentsphp-8

file_get_contents does not seem to work after PHP 8.0 update


I have no idea if this is related to a newly update on my web servers to PHP 8.0 from 7.4, but this seems to have happened after the update.

I am retrieving JSON (and decoding it) from another URL. But after the update the file_get_contents returns nothing - its empty.

This is what I have tried to locate the problem:

$json = file_get_contents("https://www.example.com/json.php"); // not actual link
echo $json . "<br>";

$dataArray = json_decode($json);
echo var_dump($dataArray);

The first echo is just blank and the second echo is NULL.

What could be wrong here? This is at the TOP of the page, so no code is prior to this.

EDIT I added the code to get errors and this is the start of what I got:

Warning: file_get_contents(https://www.example.com/json.php): Failed to open stream: HTTP request failed! HTTP/1.1 406 Not Acceptable

EDIT 2

The suggested solution is that I add the $ctxvariable to file_get_contents, but I still get the same error.

$ctx = stream_context_create(['http' => ['protocol_version' => '1.0']]);
echo file_get_contents('https://LINKHERE.com', false, $ctx);

Solution

  • I had to use cURL instead of file_get_contentsas the HTTP/1.1 somehow made the use of file_get_contents impossible. Thank you to all of you who used time to help me with this issue!