HTTP protocol's PUT and DELETE and their usage in PHP
Asked Answered
N

6

80

Introduction

I've read the following:

Hypertext Transfer Protocol (HTTP) is the life of the web. It's used every time you transfer a document, or make an AJAX request. But HTTP is surprisingly a relative unknown among some web developers.

The HTTP verbs comprise a major portion of our “uniform interface” constraint and provide us the action counterpart to the noun-based resource. The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, and DELETE.

Huh?

Well, we came to the point I lost track of things.

PUT and DELETE, they say. I've only ever heard of POST and GET and never saw something like $_PUT or $_DELETE passing by in any PHP code I've ever viewed.

My question

What are these methods (PUT) and (DELETE) for and if it's possible to use them in PHP, how would I go about this.

Note: I know this is not really a problem but I always grab a learning opportunity if I see one and would very much like to learn to use these methods in PHP if this is possible.

Necrophilia answered 14/1, 2015 at 10:53 Comment(1)
(Interesting question. Aside: if you are posting in a fragment of a website or book, it helps to quote it, to show it is not your text but someone else's. This adds context that makes a question more readable).Epagoge
D
76

What are these methods (PUT) and (DELETE) for...

There are a lot of words to spend to explain this, and I'm not skilled enough to do it, but as already posted, a quick recap of what the HTTP specification describes.

The protocol basically says this:

  • use GET when you need to access a resource and retrieve data, and you don't have to modify or alter the state of this data.

  • use POST when you need to send some data to the server. Ex. from a form to save these data somewhere.

  • use HEAD when you need to access a resource and retrieve just the Headers from the response, without any resource data.

  • use PUT when you need to replace the state of some data already existing on that system.

  • use DELETE when you need to delete a resource (relative to the URI you've sent) on that system.

  • use OPTIONS when you need to get the communication options from a resource, so for checking allowed methods for that resource. Ex. we use it for CORS request and permissions rules.

  • You can read about the remaining two methods on that document, sorry I've never used it.

Basically a protocol is a set of rules you should use from your application to adhere to it.


... and if it's possible to use them in PHP, how would I go about this.

From your php application you can retrieve which method was used by looking into the super global array $_SERVER and check the value of the field REQUEST_METHOD.

So from your php application you're now able to recognize if this is a DELETE or a PUT request, ex. $_SERVER['REQUEST_METHOD'] === 'DELETE' or $_SERVER['REQUEST_METHOD'] === 'PUT'.

* Please be also aware that some applications dealing with browsers that don't support PUT or DELETE methods use the following trick, a hidden field from the html form with the verb specified in its value attribute, ex.:

<input name="_method" type="hidden" value="delete" />

Follow an example with a small description on a possible way to handle those 2 http requests

When you (your browser, your client) request a resource to an HTTP server you must use one of the method that the protocol (HTTP) accepts. So your request needs to pass:

  • A METHOD
  • An Uri of the resource
  • Request Headers, like User-Agent, Host, Content-Length, etc
  • (Optional body of the request)

Now, while you would be able to get data from POST and GET requests with the respective globals ($_GET, $_POST), in case of PUT and DELETE requests PHP doesn't provide these fast access globals; But you can use the value of $_SERVER['REQUEST_METHOD'] to check the method in the request and handle your logic consequently.

So a PUT request would look like:

PUT /something/index.php

(body) maybe=aparameter

and you can access those data in PHP by reading the php://input stream, ex. with something like:

if ($_SERVER['REQUEST_METHOD'] === 'PUT') { 
    $myEntireBody = file_get_contents('php://input'); //Be aware that the stream can only be read once
}

and a DELETE request would look like:

DELETE /something/index.php?maybe=aparameter

and again you can build your logic after have checked the method:

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') { 
    // do something
}

Please pay attention that a DELETE request has no Body and pay very attention to Response Status Code too (ex. if you received a PUT request and you've updated that resource without error you should return a 204 status -No content-).

Decumbent answered 14/1, 2015 at 14:0 Comment(3)
The question asks how to use PUT and DELETE, and this answer explains how to use GET and POSTActinon
thanks, your comment is partly right and I've updated my answer.Decumbent
A very nice answer. Thanks. I think some words about the 'PATCH' verb can be added.Paapanen
A
44

Way to use PUT data from PHP:

$method = $_SERVER['REQUEST_METHOD'];
if ('PUT' === $method) {
    parse_str(file_get_contents('php://input'), $_PUT);
    var_dump($_PUT); //$_PUT contains put fields 
}
Aseptic answered 31/1, 2017 at 13:44 Comment(2)
The [PHP Manual]: php.net/manual/en/features.file-upload.put-method.php recommends the technique in this answer for PUT requests. I could not find a manual page for DELETE requests, and found that I could only retrieve data from the query string ($_GET) rather than any type of stream (like php://input). The PHP manual page mentions updating the server config (Apache specifically), but it was not necessary for CentOS7/PHP7/httpd2.4.6.Bull
Damn, it's 2018. Why there's still no straightforward support of PUT in PHP.Abdullah
L
25

PHP's $_GET and $_POST are poorly named. $_GET is used to access the values of query string parameters, and $_POST lets you access the request body.

Using query string parameters is not limited to GET requests, and other kinds of requests than just POST can come with a request body.

If you want to find out the verb used to request the page, use $_SERVER['REQUEST_METHOD'].

Luana answered 14/1, 2015 at 10:58 Comment(0)
E
13

Most suitable place to use these (PUT and DELETE) methods is REST API. Where we use http methods to define the mode of operation for example you want to fetch any resources then you can use following:

GET http://api.example.com/employee/<any_id>

to add a new item:

POST http://api.example.com/employee/

to Update or Edit:

PUT http://api.example.com/employee/

to Delete an existing resource:

DELETE http://api.example.com/employee/1

etc.

Now on PHP side you just need to read what HTTP method used so that you can make an action according to that.

There are lots of libraries available which can do that for you.

Ecbolic answered 19/1, 2015 at 10:27 Comment(0)
T
10

What are these methods (PUT) and (DELETE)

There are described in the HTTP spec.

In a nutshell, and simplifying somewhat, PUT is for uploading a file to a URL and DELETE is for deleting a file from a URL.

never sawy something like $_PUT or $_DELETE passing by in any PHP code I've ever viewed

$_POST and $_GET are terribly named superglobals. $_POST is for data parsed from the request body. $_GET is for data parsed from the URL. There's nothing that strictly ties data in either of those places (especially the URL) to a particular request method.

DELETE requests only care about the URL's path, so there is no data to parse.

PUT requests usually care about the entire request body (not a parsed version of it) which you would access with file_get_contents('php://input');.

for and if it's possible to use them in PHP, how would I go about this.

You'd need to map the URL onto a PHP script (e.g. with URL rewriting), test the request method, work out what URL you were actually dealing with, and then write code to do the appropriate action.

Threlkeld answered 14/1, 2015 at 10:59 Comment(2)
I would be cautious about saying uploading and deleting a "file". Technically it affects the "resource" identified by the URI (aka URL) which may or may not be a physical file. Typically in REST scenarios this often refers to a database entity.Newson
RFC 2616 is obsolete. Please cite RFC 7231.Marcelmarcela
B
1
$GLOBALS["_PUT"]=null;
if($_SERVER['REQUEST_METHOD'] == 'PUT') {
    $form_data= json_encode(file_get_contents("php://input"));
    $key_size=52;
    $key=substr($form_data, 1, $key_size);
    $acc_params=explode($key,$form_data);
    array_shift($acc_params);
    array_pop($acc_params);
    foreach ($acc_params as $item){
        $start_key=' name=\"';
        $end_key='\"\r\n\r\n';
        $start_key_pos=strpos($item,$start_key)+strlen($start_key);
        $end_key_pos=strpos($item,$end_key);
        
        $key=substr($item, $start_key_pos, ($end_key_pos-$start_key_pos));
        
        $end_value='\r\n';
        $value=substr($item, $end_key_pos+strlen($end_key), -strlen($end_value));
        $_PUT[$key]=$value;
    }
    $GLOBALS["_PUT"]=$_PUT;
}

if (!function_exists("getParameter")){
    function getParameter($parameter)
    {
        $value=null;
        if(($_SERVER['REQUEST_METHOD'] == 'POST')&& (isset($_POST[$parameter]))){
            $value=$_POST[$parameter];
        }
        else if(($_SERVER['REQUEST_METHOD'] == 'PUT')&& (isset($GLOBALS["_PUT"][$parameter])))
        {
                $value=$GLOBALS["_PUT"][$parameter];
        }
        else if(($_SERVER['REQUEST_METHOD'] == 'DELETE')&& (isset($_DELETE[$parameter]))){
            $value=$_DELETE[$parameter];
        }
        else if(($_SERVER['REQUEST_METHOD'] == 'PATCH')&& (isset($_PATCH[$parameter]))){
            $value=$_PATCH[$parameter];
        }
        else if(isset($_GET[$parameter])){
            $value=$_GET[$parameter];
        }
        return $value;
    }
}   
Brobdingnagian answered 12/8, 2022 at 17:19 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Zee

© 2022 - 2024 — McMap. All rights reserved.