PHPから直接リクエストをPOSTする際に、file_get_contentsを使うと「Content-type not specified assuming application/x-www-form-urlencoded」エラーになる場合の対処
以下の記述だと上記エラーが表示されます。
$url = 'http://test.co.jp';
$data =array();
$data = http_build_query($data, "", "&");
$options =array(
'http' =>array(
'method' => 'POST',
'content' => $data
)
);
$contents =file_get_contents($url, false, stream_context_create($options));
どうも、ヘッダー情報がない旨のエラーのようなので、ヘッダー指定を追加。
$url = 'http://test.co.jp';
$data =array();
$data = http_build_query($data, "", "&");
$header = array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($data)
);
$options =array(
'http' =>array(
'method' => 'POST',
'header' => implode("\r\n", $header),
'content' => $data
)
);
$contents =file_get_contents($url, false, stream_context_create($options));
これで、正常にリクエストできました。
以上