の以前の応答
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);}
間違っている。この関数は時々機能しますが、不正確であり、Content-type of application / x-www-form-urlencodedを使用しておらず、ユーザー名とパスワードを渡した場合は失敗します。
application / x-www-form-urlencodedがデフォルトのContent-typeであるため、ライターにとっては機能していますが、ユーザー名とパスワードの処理により、以前のコンテンツタイプの宣言が上書きされています。
修正された関数は次のとおりです。
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'。=(ドットは配列要素に追加するのと同じです。)