使用身份验证和file_get_contents()

使用file_get_contents()获取文件的内容是一个相当普遍的做法。这可能只是为了获取文本文件的内容或使Drupal中的ImageCache模块预先缓存图像。该file_get_contents()函数可以获取本地文件或远程文件,并且通常以这种方式运行。

$data = file_get_contents($url);

但是,当尝试使用此功能与经过身份验证的服务器通信时,您会看到以下错误出现。

Warning: file_get_contents(http://www.example.com/test.php): failed to open stream: HTTP request failed! 
HTTP/1.1 401 Authorization Required intest.phpon line 4

要解决此问题,您将需要向该file_get_contents()函数传递第三个参数,以使该函数使用上下文。该上下文将向服务器传递一个附加的Authorization标头,并通过一个名为的函数创建该上下文stream_context_create()。这是您需要以file_get_contents()身份验证方式使用的所有代码。

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

第二个参数用于添加标志,此处使用空值将其跳过,但是false也适用。有关可用的标志的更多信息,请参见file_get_contents()PHP手册上的页面。