Using file_get_contents to Authenticate and Access an htaccess Protected File

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

<?php
 $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

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *