Oftentimes, file_get_contents()
function comes really handy when we are trying to pull data from an API. We can simply do it by doing this:
$json_data = file_get_contents('http://theurl.com/api/json');
But what if the API requires authentication? Then, you’ll need a way to communicate with the authenticated server or else the server will give you this response.
Warning: file_get_contents(http://www.yourdomain.com/file.php): failed to open stream: HTTP request failed!
HTTP/1.1 401 Authorization Required in file.php on line 7
In order to avoid that, first we need a way to add the username and password to the HTTP header in the request. We can simply use the stream_context_create()
function.
Next is to use that stream context in the file_get_contents() function as the third parameter. As for the second parameter, just simply use false or 0 to skip it.
$username = 'theusername';
$password = 'thepassword';
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode("$username:$password")
)
));
$json_data = file_get_contents('https://theurl.com/api/json', false, $context);