11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[PHP] file_get_contentsを使ってPOSTするときに「Content-type not specified assuming application/x-www-form-urlencoded」エラーになる

Last updated at Posted at 2015-10-09

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));

これで、正常にリクエストできました。

以上

11
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?