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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7732634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:16:06  来源:igfitidea点击:

Making a HTTP GET request with HTTP-Basic authentication

phphttpbasic-authentication

提问by Naftuli Kay

I need to build a proxy for a Flash Player project I'm working on. I simply need to make a HTTP GET request with HTTP-Basic authentication to another URL, and serve the response from PHP as if the PHP file was the original source. How can I do this?

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

采纳答案by Marc B

Using file_get_contents()with a streamto specify the HTTP credentials, or use curland the CURLOPT_USERPWDoption.

file_get_contents()与 astream一起使用以指定 HTTP 凭据,或curlCURLOPT_USERPWD选项一起使用。

回答by clone45

Marc B did a great job of answering this question. I recently took his approach and wanted to share the resulting code.

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);

?>

I hope that this is helpful to people!

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

回答by Ben

I took @clone45's code and turned it into a series of functions somewhat like Python's requestsinterface (enough for my purposes) using only no external code. Maybe it can help someone else.

我采用了@clone45 的代码并将其转换为一系列函数,有点像 Python 的请求接口(足以满足我的目的),只使用不使用外部代码。也许它可以帮助别人。

It handles:

它处理:

  • basic auth
  • headers
  • GET Params
  • 基本认证
  • 标题
  • 获取参数

Usage:

用法:

$url = 'http://sweet-api.com/api';
$params = array('skip' => 0, 'top' => 5000);
$header = array('Content-Type' => 'application/json');
$header = addBasicAuth($header, getenv('USER'), getenv('PASS'));
$response = request("GET", $url, $header, $params);
print($response);

Definitions

定义

function addBasicAuth($header, $username, $password) {
    $header['Authorization'] = 'Basic '.base64_encode("$username:$password");
    return $header;
}

// method should be "GET", "PUT", etc..
function request($method, $url, $header, $params) {
    $opts = array(
        'http' => array(
            'method' => $method,
        ),
    );

    // serialize the header if needed
    if (!empty($header)) {
        $header_str = '';
        foreach ($header as $key => $value) {
            $header_str .= "$key: $value\r\n";
        }
        $header_str .= "\r\n";
        $opts['http']['header'] = $header_str;
    }

    // serialize the params if there are any
    if (!empty($params)) {
        $params_array = array();
        foreach ($params as $key => $value) {
            $params_array[] = "$key=$value";
        }
        $url .= '?'.implode('&', $params_array);
    }

    $context = stream_context_create($opts);
    $data = file_get_contents($url, false, $context);
    return $data;
}

回答by Zamboo

You really want to use php for that ?

您真的想为此使用 php 吗?

a simple javascript script does it:

一个简单的 javascript 脚本可以做到:

function login(username, password, url) {

  var http = getHTTPObject();

  http.open("get", url, false, username, password);
  http.send("");
  //alert ("HTTP status : "+http.status);

  if (http.status == 200) {
    //alert ("New window will be open");
    window.open(url, "My access", "width=200,height=200", "width=300,height=400,scrollbars=yes");
    //win.document.location = url;
  } else {
    alert("No access to the secured web site");
  }

}

function getHTTPObject() { 

  var xmlhttp = false;
  if (typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  } else {
    /*@cc_on
    @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
    @end @*/
  }
  return xmlhttp;
}