以下の関数を使用して、fopen を使用して POST 経由で JSON データを送信しようとしています。
function doPostRequest($url, $data, $optional_headers = null)
{
$params = array(
'http' => array(
'method' => 'POST',
'content' => $data,
'header' => 'Content-type: application/json' . "\r\n"
. 'Content-Length: ' . strlen($data) . "\r\n"
)
);
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
try {
$fp = fopen($url, 'rb', false, $ctx);
$response = stream_get_contents($fp);
} catch (Exception $e) {
echo 'Exception: ' . $e->getMessage ();
}
return $response;
}
$json_data = array(
'first_name' => 'John',
'last_name' => 'Doe'
);
$content = urlencode(json_encode($json_data));
doPostRequest($url, $content);
エラーは発生しませんが、データをデコードしようとする$input_stream
と空になります。なんで?私は何が欠けていますか?
$input_stream = file_get_contents('php://input');
$json = urldecode($input_stream);
var_dump($input_stream);
編集: コードは XAMPP がインストールされているマシンでは動作しますが、別のマシンでは動作しません。サーバーの構成が関係している可能性はありますか?