If I am issuing an HTTP DELETE, how can I access the PHP body/variable? I know if you\'re issuing POST, you access it via $_POST[\'varname\']
, but how do you access
I don't think you can access it in a globally available array, but you can determine the request typer, see here: Detecting request type in PHP (GET, POST, PUT or DELETE)
As stated by people above, PHP does not have a global variable to quickly access data in a DELETE
request. Why, I do not know; it probably hasn't been as used as GET
and POST
historically.
You would have to check the request type using $_SERVER['REQUEST_METHOD']
and then retrieve the entire body using the php://input
stream and extract your data from that. You could create a function that does this on every request and saves it in a global variable named $_DELETE
if you would like to keep a similar look to your code (assuming you use $_POST
and $_GET
). You could even patch your PHP to do this and compiling your own version of PHP, but that would of course confuse people who try to run your code on another PHP installation :)
file_get_contents('php://input') should always give you the complete request body. Note that it may be readable only once. The bigger question is whether a DELETE request may contain a body, which seems to be something of an unanswered question, but will probably work.
I'd say sending the id in the body is somewhat RESTless though. The entity in question should be referred to by the URL as example.com/foo/42
, so a DELETE request should say DELETE /foo/42
, not DELETE /foo
with the id in the request body.
You might have to look at reading the data directly from the php://input
stream.
I knwo this is how you have to do it for PUT
requests and some quick googling indicates the method works for DELETE
as well.
See here for an example. The comment here says this method works for DELETE
also.
Here is an interesting code sample that will help (from sfWebRequest.class.php of the symfony 1.4.9 framework altered slight for brevity):
public function initialize(...)
{
... code ...
$request_vars = array();
if (isset($_SERVER['REQUEST_METHOD']))
{
switch ($_SERVER['REQUEST_METHOD'])
{
case 'PUT':
if ('application/x-www-form-urlencoded' === $this->getContentType())
{
parse_str($this->getContent(), $request_vars );
}
break;
case 'DELETE':
if ('application/x-www-form-urlencoded' === $this->getContentType())
{
parse_str($this->getContent(), $request_vars );
}
break;
}
... more code ...
}
public function getContent()
{
if (null === $this->content)
{
if (0 === strlen(trim($this->content = file_get_contents('php://input'))))
{
$this->content = false;
}
}
return $this->content;
}
This code sample puts the PUT
or DELETE
request parameters into the $request_vars
array. A limitation appears to be that the form (if you are using one other the content-type header) must be 'application/x-www-form-urlencoded', some quick googling confirms this.