using file_get_contents to authenticate and access

2019-03-24 06:05发布

问题:

This question already has an answer here:

  • Making a HTTP GET request with HTTP-Basic authentication 4 answers

I need to reach a foreign .php page protected by a regular .htaccess file (Auth type Basic, htpasswords etc...).

I'd like to send the user and password needed through the request. Is it possible? I would like to avoid cURL and all pecl_http dependent functions if possible...

回答1:

Off-hand, I believe you can use a context to do that:

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