Read the original request body for multipart / form-data with php in PUT, PATCH, DELETE ... request

I am writing a soothing api library from scratch, and now I'm stuck in a common problem: read the raw data from multipart / form-data from the request.

For POST requests, I know I have to use $_FILE/ variables $_POST. But what if there is a PUT , PATCH, or any other type of request other than POST?

  • Is it possible?
  • If so, how can I read a raw body because, according to the documentation , it is not available in php://input?

Note. I was looking for input format and how to read it, I just want to access RAW data.

+4
source share
3 answers

But what if there is a PUT, PATCH, or any type of request other than POST?

Well, as you develop the API , if you choose , whether it takes only POST, PUT, POST+ PUTor any other combination of request headers.

An API should not be designed to “accept and process” everything that a third-party application sends to your API. This is an application (I mean an application that connects to the API) to prepare the request in such a way that the API accepts it.

, ( , -) (, , ..). , , API, , -, .

- @Adil Abbasi, , ( php://input). , php://input enctype = "multipart/form-data" .

<?php
$input = file_get_contents('php://input');
// assuming it JSON you allow - convert json to array of params
$requestParams = json_decode($input, true);
if ($requestParams === FALSE) {
   // not proper JSON received - set response headers properly
   header("HTTP/1.1 400 Bad Request"); 
   // respond with error
   die("Bad Request");
}

// proceed with API call - JSON parsed correctly

enctype = "multipart/form-data" - STDIN - docs :

<?php
$bytesToRead = 4096000;
$input = fread(STDIN, $bytesToRead ); // reads 4096K bytes from STDIN
if ($input === FALSE) {
   // handle "failed to read STDIN"
}
// assuming it json you accept:
$requestParams = json_decode($input , true);
if ($requestParams === FALSE) {
   // not proper JSON received - set response headers properly
   header("HTTP/1.1 400 Bad Request"); 
   // respond with error
   die("Bad Request");
}
+5

PUT stdin, :

        // Parse the PUT variables
        $putdata = fopen("php://input", "r");
        $put_args    = parse_str($putdata);

:

        // PUT variables
        parse_str(file_get_contents('php://input'), $put_args);
+1

you can use this code snippet to get parameters in array format.

  $params = array();
  $method = $_SERVER['REQUEST_METHOD'];

  if ($method == "PUT" || $method == "DELETE") {
      $params = file_get_contents('php://input');

      // convert json to array of params
      $params = json_decode($params, true);
  }
0
source

All Articles