Getting PUT Request's Body in PHP
Why?x
I am currently building a REST-like API for a CMS and one of the concepts is to use HTTP requests to access and send data. HTTP Request includes POST, GET, PUT and DELETE.
In php, when we try to access the POST Request's body, we just use the $_POST variable
and the syntax is something like this:
your body(in json):
{name: "xander", age:3}
in your php after POST request:
$_POST['name'] <-- this returns "xander"
$_POST['age'] <-- this returns 3
It's good if this also works with PUT... right?
But it doesn't.
I don't have a very clear explanation why they didn't implemented it, but if it only works on GET and POST, it's kinda weird... (maybe because i'm just bad)
Workarounds
Based on PHP: PUT method support you want to implement it like this:
$putfp = fopen('php://input', 'r');
Usage:
$putfp = fopen('php://input', 'r');
$putdata = '';
while($data = fread($putfp, 1024))
$putdata .= $data;
fclose($putfp);But this is how i implemented it, using:
$rawBody = file_get_contents("php://input");
$body = json_decode($rawData, true);
$body now is an associative array
You can now use it like
$body['name']
$body['age']
Summary
There's no to summarize, hmmm... we can still use PUT request in php but we can't access the body like POST and GET.
Learn More:
https://www.php.net/manual/en/features.file-upload.put-method.php
https://www.rfc-editor.org/rfc/rfc7231#section-4
No comments:
Post a Comment