Php://input

Question:

Hello, I met the code

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

Is this method needed to get the contents of POST and GET requests? What has $ _POST and $ _GEt not satisfied with? Why do we need this horror at all?

Reading the article it is difficult to enter what these streams are for … No examples, no sensible presentation …. http://www.php.net/manual/ru/wrappers.php.php

Answer:

For example, you need to send json a serialized string. You need to transfer this via POST, because in GET the length of this very string is limited, it seems, by 4 kilobytes.

What exactly is passed by the POST method?

And this is what is transmitted:

POST /test/script.php HTTP/1.1
Host: site.com
Content-Length: xxxx
... и другие заголовки..

paramName1=paramValue1&paramName2=paramValue2...

I don’t want to transfer something like: abc=<json_string> , because this string also needs to be escaped.

So we just feed the string to the script. Something like this will come to the server:

POST /test/script.php HTTP/1.1
Host: site.com
Content-Length: xxxx
... и другие заголовки..

{"paramName1": "paramValue2","paramName2": "paramValue2",...}

Naturally, the server cannot parse such requests, so file_get_contents('php://input');

We can get what was sent to us without changes, parse it ourselves and be happy 🙂

Scroll to Top