php获取post中的json数据

2015.10.15 php获取post中的json数据已关闭评论

最近用到python与PHP交互,python把json数据 post给PHP,但在PHP里面$_post获取不到,$_REQUEST也获取不到,但是通过firedebug看到的请求信息确实是把JSON数据 post给了PHP,这什么情况...突然想到了以前接触过flash将图片二进制流传给php,灵机一动 用$GLOBALS['HTTP_RAW_POST_DATA']获取到了。于是就深入的查了一下,原来PHP默认只识别application/x-www.form-urlencoded标准的数据类型,因此,对型如text/xml 或者 soap 或者 application/octet-stream 之类的内容无法解析,如果用$_POST数组来接收就会失败!故保留原型,交给$GLOBALS['HTTP_RAW_POST_DATA'] 来接收。

 

用Content-Type=text/xml 类型,提交一个xml文档内容给了php server,要怎么获得这个POST数据。

The RAW / uninterpreted HTTP POST information can be accessed with:   $GLOBALS['HTTP_RAW_POST_DATA'] This is useful in cases where the post Content-Type is not something PHP understands (such as text/xml).

由于PHP默认只识别application/x-www.form-urlencoded标准的数据类型,因此,对型如text/xml的内容无法解析为$_POST数组,故保留原型,交给$GLOBALS['HTTP_RAW_POST_DATA'] 来接收。

另外还有一项 php://input 也可以实现此这个功能

php://input 允许读取 POST 的原始数据。和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。php://input 不能用于 enctype="multipart/form-data"

应用测试

php发送:

<?php
function http_post_json($url, $jsonStr)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($jsonStr)
)
);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

return array($httpCode, $response);
}

$url = "http://www.liwuguan.cn/getjson.php";
$jsonStr = json_encode(array('a' => 1, 'b' => 2));
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
var_dump($returnCode);
var_dump($returnContent);

php接收:

<?php
$str= file_get_contents("php://input");
file_put_contents('json.txt',$str);

?>

 

 

Related Posts:

评论已关闭。