Handling PUT/DELETE arguments in PHP Handling PUT/DELETE arguments in PHP codeigniter codeigniter

Handling PUT/DELETE arguments in PHP


Instead of using CURLOPT_PUT = TRUE use CURLOPT_CUSTOMREQUEST = 'PUT' and CURLOPT_CUSTOMREQUEST = 'DELETE' then just set values with CURLOPT_POSTFIELDS.


Here is some code which may be helpful for others wanting to handle PUT and DELETE params. You are able to set $_PUT and $_DELETE via $GLOBALS[], but they will not be directly accessible in functions unless declared global or accessed via $GLOBALS[]. To get around this, I've made a simple class for reading GET/POST/PUT/DELETE request arguments. This also populates $_REQUEST with PUT/DELETE params.

This class will parse the PUT/DELETE params and support GET/POST as well.

class Params {  private $params = Array();  public function __construct() {    $this->_parseParams();  }  /**    * @brief Lookup request params    * @param string $name Name of the argument to lookup    * @param mixed $default Default value to return if argument is missing    * @returns The value from the GET/POST/PUT/DELETE value, or $default if not set    */  public function get($name, $default = null) {    if (isset($this->params[$name])) {      return $this->params[$name];    } else {      return $default;    }  }  private function _parseParams() {    $method = $_SERVER['REQUEST_METHOD'];    if ($method == "PUT" || $method == "DELETE") {        parse_str(file_get_contents('php://input'), $this->params);        $GLOBALS["_{$method}"] = $this->params;        // Add these request vars into _REQUEST, mimicing default behavior, PUT/DELETE will override existing COOKIE/GET vars        $_REQUEST = $this->params + $_REQUEST;    } else if ($method == "GET") {        $this->params = $_GET;    } else if ($method == "POST") {        $this->params = $_POST;    }  }}


Just remember, most webservers do not handle PUT & DELETE requests. Since you're making a library, I'd suggest thinking about accounting for this. Typically, there are two conventions you can use to mimic PUT & DELETE via POST.

  1. use a custom POST variable (ex. _METHOD=PUT) which overrides POST
  2. set a custom HTTP header (ex. X-HTTP-Method-Override: PUT)

Generally speaking, most RESTful services that don't allow PUT & DELETE directly will support at least one of those strategies. You can use cURL to set a custom header if you need via the CURLOPT_HTTPHEADER option.

// ex...curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT') );