I'm new to PHP,JSON,js.
I have a js program that will send JSON string to PHP
I have some problem when using the json_decode fn inside PHP.
I try to save the string receive from JS into a file, and the json string is correct without any problem.
But when i try to use json_decode, the function hang (i think, since anything below the function call are not called at all, all my echo/print did not give anything.
Below is my js code:
function post()
{
var test1 = {
name:"marzzuq",
age:16
};
myjson = JSON.stringify(test1);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","post.php",true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(myjson);
console.log("\nsend ok: " + myjson);
}
and below is my php script:
<?php
$rawdata = file_get_contents('php://input');
file_put_contents('/tmp/test.json', $rawdata);
$jsson = json_decode($rawdata);
file_put_contents('/tmp/test3.json', $jsson);
`echo test >> /tmp/test.txt`;
?>
I have tried to use htmlentities and html_entity_decode:
$result= htmlentities((string)$rawdata);
$result2 = html_entity_decode((string)$rawdata);
and use the result on json_decode
but it does not work.
the length fr $rawdata
is 27 (using strlen), which is correct.
I try to print the json_last_error, but like i say, all the code below the line json_decode
stop working, so nothing will get print.
switch (json_last_error()) {
case JSON_ERROR_NONE:
`echo ' - No errors' >> /tmp/test.txt`;
break;
case JSON_ERROR_DEPTH:
`echo ' - Maximum stack depth exceeded' >> /tmp/test.txt`;
break;
case JSON_ERROR_STATE_MISMATCH:
`echo ' - Underflow or the modes mismatch' >> /tmp/test.txt`;
break;
case JSON_ERROR_CTRL_CHAR:
`echo ' - Unexpected control character found' >> /tmp/test.txt`;
break;
case JSON_ERROR_SYNTAX:
`echo ' - Syntax error, malformed JSON' >> /tmp/test.txt`;
break;
case JSON_ERROR_UTF8:
`echo ' - Malformed UTF-8 characters, possibly incorrectly encoded' >> /tmp/test.txt`;
break;
default:
`echo ' - Unknown error' >> /tmp/test.txt`;
break;
}
Can anyone help me?