早前的回应
function file_post_contents($url, $data, $username = null, $password = null) {
$postdata = http_build_query($data);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
if($username && $password)
{
$opts['http']['header'] = ("Authorization: Basic " . base64_encode("$username:$password"));
}
$context = stream_context_create($opts);
return file_get_contents($url, false, $context);}
是不正确的。此功能有时有效,但如果您不使用 application/x-www-form-urlencoded 的 Content-type 并传入用户名和密码,它会不准确并且会失败。
它对作者有用,因为 application/x-www-form-urlencoded 是默认的内容类型,但他对用户名和密码的处理覆盖了之前的内容类型声明。
这是修正后的函数:
function file_post_contents($url, $data, $username = null, $password = null){
$postdata = http_build_query($data);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => $postdata
)
);
if($username && $password)
{
$opts['http']['header'] .= ("Authorization: Basic " . base64_encode("$username:$password")); // .= to append to the header array element
}
$context = stream_context_create($opts);
return file_get_contents($url, false, $context);}
注意这一行: $opts['http']['header' .= (点等于附加到数组元素。)