Home > Backend Development > PHP Tutorial > How to Manually Parse Raw Multipart/Form-Data Data in PHP?

How to Manually Parse Raw Multipart/Form-Data Data in PHP?

DDD
Release: 2024-11-02 18:39:03
Original
248 people have browsed it

How to Manually Parse Raw Multipart/Form-Data Data in PHP?

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:

  1. Read the Raw Request Data:

    • Use file_get_contents('php://input') to read the raw data.
  2. Extract Boundary from Content Type Header:

    • Use a regular expression to capture the boundary value from the Content-Type header ($_SERVER['CONTENT_TYPE']).
  3. Split Data by Boundary:

    • Split the raw data into individual blocks using preg_split("- $boundary").
  4. Separate Blocks into Individual Fields:

    • For each block:

      • Uploaded Files:

        • Look for blocks containing application/octet-stream and extract the field name and filename.
      • Other Fields:

        • Extract the field name and value using a regular expression.

示例 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=\&quot;([^\&quot;]*)\&quot;.*stream[\n|\r]+([^\n\r].*)?$/s', $block, $matches);
    }
    else
    {
      preg_match('/name=\&quot;([^\&quot;]*)\&quot;[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
    }
    $a_data[$matches[1]] = $matches[2];
  }
}</code>
Copy after login

Usage:

<code class="php">$a_data = array();
parse_raw_http_request($a_data);
var_dump($a_data);</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template