2016-06-28 90 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