Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a PHP delete variable

Tags:

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 it if it's a DELETE not POST? Say the varname here is ID.

like image 619
aherlambang Avatar asked Mar 21 '11 07:03

aherlambang


2 Answers

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.

like image 164
xzyfer Avatar answered Oct 27 '22 00:10

xzyfer


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.

like image 24
deceze Avatar answered Oct 26 '22 23:10

deceze