HTTP protocol's PUT and DELETE and their usage in PHP
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-).
HTTP PUT, DELETE and I/O streams with PHP
No, you will need to parse the request manually. $_REQUEST
only contains data coming from GET
and POST
requests; for everything else you are on your own.
If your HTTP request has Content-Type: application/x-www-form-urlencoded
, you can parse it back into a variables array very easily with parse_str
like this:
parse_str(file_get_contents('php://input'), $vars);
print_r($vars);
You can use this content type with any HTTP method, there is no standard-imposed limitation.
Detecting request type in PHP (GET, POST, PUT or DELETE)
By using
$_SERVER['REQUEST_METHOD']
Example
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
For more details please see the documentation for the $_SERVER variable.
Http Verbs (Put, Delete, Post, Get ...) - use them not in an API
As many browsers support only GET and POST (and mostly PUT) methods you should use them.
If you will use more specific methods then you can meet some bugs from users who have some exotic homebrew browsers (mostly for mobiles).
How to get PUT content from HTTP request in PHP
While there is no official $_PUT
variable in PHP, you can create one yourself like this:
$method = $_SERVER['REQUEST_METHOD'];
if ('PUT' === $method) {
parse_str(file_get_contents('php://input'), $_PUT);
var_dump($_PUT); //$_PUT contains put fields
}
Source: https://stackoverflow.com/a/41959141/4379151
How Would You Use PUT or DELETE HTTP Requests On a Modern Website
Here's a real life example from a social media site I coded on contract:
Every user has a (username)/blog route.
GET to that route shows their entire blog (most recent several posts, and an ajax call with certain params fetches more).
POST to that route creates a new blog post on that user's blog.
After a POST, a new route is created at .../(post id)/(slug)/
A GET to that fetches that post only.
A PUT edits that post without changing the routes.
A DELETE deletes the post.
We use the same scheme for videos, comments, etc.
This is based on the REST design strategy. POST is for the creation of a new resource. PUT is for the replacement of an existing resource. DELETE deletes. GET fetches without changing the server's state.
The lack of HTML form support is not as big a deal nowadays since we ended up having to use JavaScript for form submission for other reasons anyways. And we do not have any problems related to webserver limitations, at least since Heroku removed their request routing HTTP methods limitations one year ago.
Related Topics
What Does the MySQLi_Error() Expects Parameter 1 to Be MySQLi, Null Given Mean
Dynamic Shipping Fee Based on Custom Radio Buttons in Woocommerce
Send Email with Attachment Using PHP
How to Remove 'Index.Php' from Url in Codeigniter
Call to Undefined Method Pdo::Execute()
Accessing JSON Array After JSON_Decode/Multidimensional Array
Passing Variables from PHP to JavaScript
Enabling 'Strict_Types' Globally in PHP 7
Pdoexception "Could Not Find Driver" in PHP
Laravel 3:Looking for Explanation How to Use the Model
Mysqli_Query(): Couldn't Fetch MySQLi Error
Is There a Built-In Function or Plugin to Handle Date Formatting in JavaScript
Undefined Index with PHP Sessions
Point in Polygon Algorithm Giving Wrong Results Sometimes
Best Way to Access Exchange Using PHP