2016-06-28 89 views
4

我从头开始编写一个restful api库,现在我遇到了一个常见问题:从多部分读取原始数据/来自请求的表单数据。用PUT,PATCH,DELETE ...请求读取multipart/form-data的原始请求正文

对于POST请求,我知道我应该使用$_FILE/$_POST变量。但是如果存在PUT,PATCH或者除POST之外的其他请求类型呢?

  • 这种情况可能吗?
  • 如果是这样,我怎样才能读取 的内容,因为根据documentation它不是 在php://input可用?

注:我搜索关于输入格式以及如何已经阅读它,我只是想访问原始数据

+0

我测试过和'PHP: // input'可与PUT请求,“根据文档它不是在PHP可用://输入”没有看到任何东西contradictious在文档 – cske

+0

- 我看不出它说,在文档。 – Quentin

+0

检查这个链接,如果它是有帮助的,[链接](http://stackoverflow.com/questions/9464935/php-multipart-form-data-put-request)。 –

回答

5

但是如果有一个PUT,PATCH,或任何请求类型,其他 比POST?

好吧,既然你是一个设计的API,然后你是谁决定是否它仅接受POSTPUTPOST + PUT或请求头的任何其他组合的一个。

该API不应被设计为“接受并尝试处理”第三方应用程序提交给您的API的所有内容。这是应用程序的工作(我的意思是,连接到API的应用程序)以这种方式准备请求,API接受它。请注意,启用多个请求方法(特别是那些必须以不同方式处理的请求方法)有多种处理请求的方式(例如安全性,类型等)。 这基本上意味着要么巧妙地设计一个请求处理过程,要么会遇到不同请求类型调用的API方法的问题,这会很麻烦。

如果您需要获取请求的原始内容 - @Adil Abbasi似乎在正确的轨道上(就解析php://input而言)。 但请注意,php://input不适用于enctype =“multipart/form-data”as described in the docs

<?php 
$input = file_get_contents('php://input'); 
// assuming it's 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的” - 读I/O Streams docsSTDIN,并尝试这样的:

<?php 
$bytesToRead = 4096000; 
$input = fread(STDIN, $bytesToRead); // reads 4096K bytes from STDIN 
if ($input === FALSE) { 
    // handle "failed to read STDIN" 
} 
// assuming it's 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"); 
} 
+0

谢谢你的I/O流引用。实际上,我正在编写一个开源库,[this](https://github.com/Corviz/framework/blob/master/src/Http/RequestParser/MultipartFormDataParser.php#L21)是我如何处理'multipart/form-data'请求......因为它可以在第三方应用中使用,所以我想支持这些请求。 – CarlosCarucce

+1

正如我所说 - 这是你的选择,也许这是一个合理的选择。只记得仔细设计请求处理过程,你会没事的。 – Kleskowy

1

PUT数据来自标准输入,就解析原始数据给一个变量:

 // 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); 
0

你可以利用此代码段,让把数组形式PARAMS 。

$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

downvaote的原因? –

+0

@CarlosCarucce请试试这个更新的代码片段,对我来说:) –

+0

做工精细嗨。非常有趣,但是,'multipart/form-data'请求怎么样?顺便说一句,我很抱歉,但不是我低估了它。 – CarlosCarucce