Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get http request body data in codeigniter?

Tags:

codeigniter

I am having trouble getting JSON encoded data POSTed to my CI controller from my IOS obj-c client. I believe that my problem is the same as the one mentioned here. But I cannot find any documentation on a 'request' object on the CodeIgniter site. How can I view/parse the data in an http request body?

$this->request->body ??

Thanks!

like image 219
Nick Avatar asked Feb 19 '12 04:02

Nick


People also ask

How do I get post data in CI?

you can simply get all post data using $this->input->post() and $_POST using simple php stuff.

What does request body contain?

When you need to send data from a client (let's say, a browser) to your API, you send it as a request body. A request body is data sent by the client to your API. A response body is the data your API sends to the client.


3 Answers

I was able to get this working by using

$jsonArray = json_decode(file_get_contents('php://input'),true); 

The above will read the request body from the input request and then decodes the JSON to an associative array.

I would still be interested in refactoring this code if CI has a wrapper for reading input stream http body data as I am above. Fairly new to this framework.

like image 96
Nick Avatar answered Oct 12 '22 01:10

Nick


Try to use $this->input->raw_input_stream

like image 23
Tan Trinh Avatar answered Oct 12 '22 01:10

Tan Trinh


The "request" object mentioned in that post belongs to a package named "codeigniter-restserver". You can find more info here.

The accepted answer is a working one, but CodeIgniter does provide $this->input->raw_input_stream that gives you exactly what you need. So to write things the CodeIgniter way, you should use:

$jsonArray = json_decode($this->input->raw_input_stream, true);

And you'll notice that the source code of raw_input_stream also uses the file_get_contents('php://input') method.

like image 39
Mu-Tsun Tsai Avatar answered Oct 12 '22 03:10

Mu-Tsun Tsai