使用HTTP-Basic身份验证发出HTTP GET请求

Naf*_*Kay 27 php http basic-authentication

我需要为我正在研究的Flash Player项目构建代理.我只需要使用HTTP-Basic身份验证向另一个URL发出HTTP GET请求,并从PHP提供响应,就像PHP文件是原始源一样.我怎样才能做到这一点?

clo*_*e45 86

Marc B在回答这个问题方面做得很好.我最近采用了他的方法,并希望分享生成的代码.

<?PHP

$username = "some-username";
$password = "some-password";
$remote_url = 'http://www.somedomain.com/path/to/file';

// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header' => "Authorization: Basic " . base64_encode("$username:$password")                 
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents($remote_url, false, $context);

print($file);

?>
Run Code Online (Sandbox Code Playgroud)

我希望这对人们有所帮助!

  • 不,他回答这个问题做得不好.你做得很好.(投票计数与我同意!) (2认同)

Mar*_*c B 13

使用file_get_contents()a stream指定HTTP凭据,或使用curlCURLOPT_USERPWD选项.

  • +1 - 还要注意,如果您没有流支持(PHP4)或cURL扩展不可用,您可以使用`http:// user:pass @ domain.tld/file` URL语法和`file_get_contents() `它将提供HTTP基本身份验证功能. (16认同)