Home > Backend Development > PHP Tutorial > How to Manually Parse Raw Multipart/Form-Data Data with PHP for PUT Requests?

How to Manually Parse Raw Multipart/Form-Data Data with PHP for PUT Requests?

Barbara Streisand
Release: 2024-10-29 03:03:02
Original
539 people have browsed it

How to Manually Parse Raw Multipart/Form-Data Data with PHP for PUT Requests?

Manually Parsing Raw Multipart/Form-Data Data with PHP

Parsing raw HTTP request data formatted in multipart/form-data can be challenging when dealing with PUT requests in PHP. The following provides a detailed explanation and a custom parsing solution:

Background

By default, PHP automatically parses POST request data if formatted correctly. However, PUT requests require manual parsing of raw data. Multipart/form-data format structures the data into blocks separated by boundaries.

Manual Parsing Function

The following function parses raw HTTP request data manually:

<code class="php">function parse_raw_http_request(array &$a_data)
{
  // Read incoming data
  $input = file_get_contents('php://input');

  // Extract boundary from content type header
  preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);
  $boundary = $matches[1];

  // Split data by boundary
  $a_blocks = preg_split("/-$boundary/", $input);
  array_pop($a_blocks);

  // Loop through data blocks
  foreach ($a_blocks as $id => $block)
  {
    // Skip empty blocks
    if (empty($block))
      continue;

    // Parse uploaded files
    if (strpos($block, 'application/octet-stream') !== FALSE)
    {
      // Extract name and file contents
      preg_match('/name=\&quot;([^\&quot;]*)\&quot;.*stream[\n|\r]+([^\n\r].*)?$/s', $block, $matches);
    }
    // Parse other fields
    else
    {
      // Extract name and value
      preg_match('/name=\&quot;([^\&quot;]*)\&quot;[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
    }

    // Add data to array
    $a_data[$matches[1]] = $matches[2];
  }  
}</code>
Copy after login

Usage:

Call the function and pass the data array by reference:

<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 with PHP for PUT Requests?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template