Manually Parsing Raw Multipart/Form-Data Data in PHP
When processing data from HTTP PUT requests with multipart/form-data format, PHP does not automatically parse the raw data. Consequently, developers may encounter challenges in extracting information from such requests.
Solution:
Read the Raw Request Data:
Extract Boundary from Content Type Header:
Split Data by Boundary:
Separate Blocks into Individual Fields:
For each block:
Uploaded Files:
Other Fields:
示例 Code:
<code class="php">function parse_raw_http_request(array &$a_data) { $input = file_get_contents('php://input'); preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches); $boundary = $matches[1]; $a_blocks = preg_split("/-+$boundary/", $input); array_pop($a_blocks); foreach ($a_blocks as $id => $block) { if (empty($block)) continue; if (strpos($block, 'application/octet-stream') !== FALSE) { preg_match('/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s', $block, $matches); } else { preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches); } $a_data[$matches[1]] = $matches[2]; } }</code>
Usage:
<code class="php">$a_data = array(); parse_raw_http_request($a_data); var_dump($a_data);</code>
The above is the detailed content of How to Manually Parse Raw Multipart/Form-Data Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!