Home / Sending a username and password with PHP file_get_contents()

Sending a username and password with PHP file_get_contents()

Last week I looked at how send a username and password with PHP CURL. Using CURL is useful because you can examine the return information to see if the request was successful etc, but if your hosting provider doesn’t have CURL for PHP enabled then you can still attempt to get the file by using file_get_contents and passing the authentication as part of the $context parameter.

In the example below, $url is the web address you want to get data from, and $username and $password are the login credentials.

$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("$username:$password")
$data = file_get_contents($url, false, $context);

If the login details were incorrect, or you were attempting to access a password protected location and didn’t pass any credentials at all, you’ll see an error like this:

Warning: file_get_contents(...): failed to open stream: HTTP request failed! 
HTTP/1.1 401 Authorization Required in ... on line 4

In future posts in this series I’ll look at how to pass other headers along with a file_get_contents() request, for example how to send a form post. Again I would mention that it’s probably better and easier to do this with CURL but if you must then it’s possible with file_get_contents().