Home > Article > Backend Development > How to POST a File String Using cURL in PHP Without Temporary Files?
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.
Analyzing a sample POST request from a browser reveals a multipart/form-data structure with a unique boundary. Replicating this format manually involves:
--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--
<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>
<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!