php POST送信時の「Content-type not specified assuming application/x-www-form-urlencoded」エラー

phpでフォームを使わずに直接POST送信したら
「Content-type not specified assuming application/x-www-form-urlencoded」
というエラーが出たのでコードを修正した際のメモ。

これはデータ送信する際のheaderが足りない!という内容のエラーらしい。エラー前は↓のような感じでメソッドタイプとデータを渡してPOSTした。

$data =array(
	'param1' => $param1,
	'param2' => $param2
);
					
$data = http_build_query($data, "", "&");
					
$options =array(
	'http' =>array(
			'method' => 'POST',
			'content' => $data
		)
	);

$contents =file_get_contents($url, false, stream_context_create($options));

修正後は、$optionsの配列にヘッダーを設定。こうすることでエラーが無くなり無事送信完了。

$data =array(
	'param1' => $param1,
	'param2' => $param2
);
					
$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));



コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>