How do I handle json data sent as an HTTP Post to a cakephp app?
cakephp
Solution
if($this->RequestHandler->requestedWith('json')) {
if(function_exists('json_decode')) {
$jsonData = json_decode(utf8_encode(trim(file_get_contents('php://input'))), true);
}
if(!is_null($jsonData) and $jsonData !== false) {
$this->data = $jsonData;
}
}
This is a codesnippet which was proposed to be in the core, see https://trac.cakephp.org/ticket/6125. Maybe it's what you're looking for.
-- Bjorn
Problem
If I'm being sent an HTTP Post where the body of the http request is just a UTF8 encoded string, how do I access that data in my cakephp controller? It appears that $this->params only contains the following: ``` { "pass":[], "named":[], "controller":"users", "action":"checkin", "plugin":null, "url":{ "ext":"json", "url":"users\/checkin.json" }, "form":[], "isAjax":false } ``` The data being posted looks something like this: ``` { "sessionkey":"somecrazykey", "longitude":"-111.12345", "latitude":"33.12345", "reqtype":"checkin", "location":"the mall", "public":"true" } ```