PHP file_get_contents可以在一台服务器上运行,但会产生授权错误

时间:2013-02-18 09:50:35

标签: php http authentication

我有一个脚本从另一个页面加载信息,使用以下代码:

    $creds = 'user:password';
$base64 = base64_encode($creds);

$base_url = 'http://example.com/page.html';
$data = file_get_contents($base_url.$path, false, $auth);

这可以从一台服务器(我的本地服务器,使用Ubuntu)正常工作但从外部服务器运行时给我以下标题:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
<hr>
<address>Apache/2.2.14 (Unix) mod_ssl/2.2.14 OpenSSL/0.9.7a DAV/2 SVN/1.6.6 PHP/5.3.14   JRun/4.0 Server at ww2.rch.org.au Port 80</address>
</body></html>

有什么特别值得我在这里找的吗?如果有帮助,我已经在两台服务器上将allow_url_fopen设置为true。

编辑:抱歉,其中还有一些需要删除的代码。 $ auth如下:

$auth = stream_context_create(array(
  'http'    => array(
  'header'  => 'Authorization: Basic '.$base64
  )
));

$ auth是一个流上下文,包含授权标题。

1 个答案:

答案 0 :(得分:3)

根据documentation of the function,没有“auth”参数。

HTTP凭据通常以这种格式添加:

http://username:password@example.com/page.html