2

I'm working on web services using REST. One of the APIs, as per the spec must be a GET request and has a Request body.

How to access the GET request body in PHP?

I tried

file_get_contents('php://input');

but no luck as it works only for POST and PUT.

Is there a way to get this done?

acj89
  • 258
  • 2
  • 6

1 Answers1

3

The concept of a request body does not make sense with GET requests. A GET request is just that, a request to fetch a bit of information. You use the URL (combined with the query string a.k.a. GET parameters, if needed) to specify which piece of information you want.

HTTP specifies that the server should just pretend your body isn't there, which is exactly what you seem to be experiencing. To quote Roy Fielding:

Any HTTP request message is allowed to contain a message body, and [the server] must thus parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. [...]

So, yes, you can send a body with GET, and no, it is never useful to do so.

(via here)

For what it's worth, the RESTClient Firefox plugin seems to ignore what you put in the Body field if you're using GET. RESTClient uses Firefox's XMLHttpRequest, which apparently ignores body data if the method is GET. I can't say I disagree.

Community
  • 1
  • 1
Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
  • Ok.. RestClient is ignoring the request body. When I did with curl it worked. Will consider your suggestion on GET requests with body. Thanks. – acj89 Mar 13 '14 at 20:57
  • 2
    To be absolutely clear: if you use data in the GET body in any way, you're immediately in violation of the HTTP protocol (which says it should have no semantic meaning, i.e. it should not matter what you put there). This in turn means you'll be the only person who can use your API. – Wander Nauta Mar 13 '14 at 21:00