Home  >  Article  >  Backend Development  >  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
Susan SarandonOriginal
2024-10-17 18:30:02232browse

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--
  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>
  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>

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!

Statement:
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