file_get_contents to get JSON data -- PHP



$params = file_get_contents('php://input');

 

For JSON data, it's much easier to POST it as "application/json" content-type. If you use GET, you have to URL-encode the JSON in a parameter and it's kind of messy. Also, there is no size limit when you do POST. GET's size if very limited (4K at most).

<?php
// SERVER

if(getenv('REQUEST_METHOD') == 'POST'
) {
$client_data = file_get_contents("php://input"
);
echo
"
<SERVER>
Hallo, I am server
This is what I've got from you
$client_data

</SERVER>
"
;

// json객체형태로 사용
$json = json_decode($client_data);

exit();
}
?>

<!-- CLIENT -->

<script>
function sendAndLoad(sURL, sXML) {
var r = null;
if(!r) try { r = new ActiveXObject("Msxml2.XMLHTTP") } catch (e){}
if(!r) try { r = new XMLHttpRequest() } catch (e){}
if(!r) return null;
r.open("POST", sURL, false);
r.send(sXML);
return r.responseText;
}
</script>

<button onclick="
alert(sendAndLoad(
location.href,
'<xml><sample>data</sample></xml>'
))">
Test
</button>

참고 : http://www.sitepoint.com/forums/showthread.php?274379-php-input-example


덧글

댓글 입력 영역