我需要为我正在进行的Flash Player项目构建一个代理。我只需要对另一个URL进行HTTP GET请求并使用HTTP基本身份验证,然后将PHP的响应作为原始来源提供。我该如何实现?
我需要为我正在进行的Flash Player项目构建一个代理。我只需要对另一个URL进行HTTP GET请求并使用HTTP基本身份验证,然后将PHP的响应作为原始来源提供。我该如何实现?
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);
?>
我希望这对人们有所帮助!
使用file_get_contents()
函数与stream
一起使用来指定HTTP凭证,或者使用curl
和CURLOPT_USERPWD
选项。
http://user:pass@domain.tld/file
URL语法与file_get_contents()
,它将提供HTTP基本身份验证功能。 - DaveRandom$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);
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;
}
json_decode
函数。 - Benfunction 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;
}
curl
很容易获取,我可能会使用它。我希望我的脚本在尽可能多的机器上“只需工作”。 - Naftuli Kay