LoginSignup
74
65

More than 3 years have passed since last update.

【PHP】JSONでPOSTされた値の取り出し方。file_get_contents("php://input") するようだ。

Last updated at Posted at 2019-06-09

$_POSTには何もなかった...

るんるん気分で普通にクライアント側からAjaxしてPHPにJSONをPOSTしました。いつも通りに。

しかし、$_POSTには何も入っていませんでした...array(0)みたいな。

公式に明記されていましたが、残念ながらPHPではPOSTデータを$_POSTで受け取れるのは「application/x-www-form-urlencoded」又は「multipart/form-data」のみとのこと。

Content-Type に application/x-www-form-urlencoded あるいは multipart/form-data を用いた HTTP リクエストで、 HTTP POST メソッドから現在のスクリプトに渡された変数の連想配列です。
PHP公式 より

じゃあどうするのというと↓らしいです。

PHPでJSONを受け取るにはこうするらしい⇒file_get_contents("php://input")

タイトルにも書いてますが、file_get_contents("php://input")するらしいです。

JSON値を受け取るサーバ側のコード

mytest-api.php
// POSTされたJSON文字列を取り出し
$json = file_get_contents("php://input");

// JSON文字列をobjectに変換
//   ⇒ 第2引数をtrueにしないとハマるので注意
$contents = json_decode($json, true);

// デバッグ用にダンプ
var_dump($contents);

php://input
で送信されたbody部を意味するので、それに対してfile_get_contentsしてあげればデータ部の文字列(JSON)が取れ、あとは普通にjson_decodeすればPHPオブジェクト(連想配列)にパースできる。

一応クライアント側も書いておきます。

$.ajax({
    type: "POST",
    url: "./mytest-api.php",
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify({
                mytestdata: "hoge"
    })
})

前も調べたから今度はちゃんと覚えよう...

74
65
0

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
74
65