Home > Backend Development > PHP Tutorial > How to POST a File String Using cURL in PHP Without Temporary Files?

How to POST a File String Using cURL in PHP Without Temporary Files?

Susan Sarandon
Release: 2024-10-17 18:30:02
Original
331 people have browsed it

How to POST a File String Using cURL in PHP Without Temporary Files?

POSTing a File String Using cURL in PHP

The task of sending a file along with other form data becomes more intricate when the file is represented solely as a string. This tutorial demonstrates how to use cURL in PHP to construct the request and bypass temporary file creation.

Solution

Analyzing a sample POST request from a browser reveals a multipart/form-data structure with a unique boundary. Replicating this format manually involves:

  1. Creating a Form Data Body: Separate the file and non-file fields and concatenate them with appropriate headers and delimiters. Example:
--boundary
Content-Disposition: form-data; name="otherfield"
Content-Type: text/plain

other field content
--boundary
Content-Disposition: form-data; name="filename"; filename="test.jpg"
Content-Type: image/jpeg

raw JPEG data
--boundary--
Copy after login
  1. Setting cURL Options: Configure cURL to handle the POST request with multipart/form-data and specify the content length.
<code class="php">$options = array(
    // Send post data over a POST request
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => array(
        // Content-type to multipart/form-data with boundary
        'Content-Type: multipart/form-data; boundary='.$delimiter,
        // Content-Length to the length of our multipart form data
        'Content-Length: ' . strlen($data)
    )
);</code>
Copy after login
  1. Execute cURL Request: Use curl_setopt to set the POST fields and execute the request.
<code class="php">curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);</code>
Copy after login

By crafting the body and setting appropriate headers, we simulate a POST request from a browser and avoid creating temporary files.

The above is the detailed content of How to POST a File String Using cURL in PHP Without Temporary Files?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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