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

时间:2011-10-11 21:17:40

标签: php http http-basic-authentication

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

4 个答案:

答案 0 :(得分:83)

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

?>

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

答案 1 :(得分:13)

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

答案 2 :(得分:1)

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

它处理:

  • basic auth
  • 标题
  • GET Params

用法:

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

解释

.val()

答案 3 :(得分:-9)

你真的想用php吗?

一个简单的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;
}
相关问题