Friday, March 1, 2013

Sending a username and password with PHP file_get_contents()

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

http://www.electrictoolbox.com/php-file-get-contents-sending-username-password/ 

No comments:

Post a Comment