Search code examples
phpjsontwitch

twitch file_get_contents php gives 404 instead of error json


I am trying to fetch user info with file_get_contents() with the use of twitch api. When I test the link in my browser with both existing and non existing, it works fine for both cases (returns user object in case user exists, and error object if user does not exist).

However, when I want to accomplish the same in PHP with file_get_contents(), it does work fine when the user exists, but when it does not, PHP throws Failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found.

My code looks like this:

$username = $_GET['username'];
$result = file_get_contents('https://api.twitch.tv/kraken/users/'.$username);
var_dump($result);

Solution

  • I think you are trying to parse the JSON no matter if there is a valid HTTP code (e.g. 200) or an invalid one (e.g. 404). The problem of PHP is here, that it fails if there is an invalid HTTP response code. You can however force PHP to accept this by using a flag in the method call. See https://stackoverflow.com/a/4132660/3233827 for that.