Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle json data sent as an HTTP Post to a cakephp app?

Tags:

cakephp

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"
}
like image 345
casper Avatar asked Nov 19 '09 21:11

casper


2 Answers

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

like image 63
Bjorn Avatar answered Sep 24 '22 21:09

Bjorn


You can use these simplest way :

$data = $this->request->input ( 'json_decode', true) ;
like image 38
Grant Fong Avatar answered Sep 25 '22 21:09

Grant Fong