Multipart Form Data: Sending File Strings in PHP with cURL
In many scenarios, developers may encounter the need to submit both form data and files using HTTP POST requests. When dealing with files stored on the filesystem, the process is straightforward: prefixing the file path with "@" in the CURLOPT_POSTFIELDS enables cURL to handle file uploads.
However, the question arises: is it possible to bypass the file creation process and directly send file content as a string using cURL?
The answer is yes, as demonstrated in the solution below. By constructing the form data body manually and setting appropriate headers, we can simulate the form submission behavior of a web browser:
<code class="php">// Form field separator $delimiter = '-------------' . uniqid(); // File upload fields: name => array(type => 'mime/type', content => 'raw data') $fileFields = array( 'file1' => array( 'type' => 'text/plain', 'content' => '...your raw file content goes here...' ), /* ... */ ); // Non-file upload fields: name => value $postFields = array( 'otherformfield' => 'content of otherformfield is this text', /* ... */ ); $data = ''; // Populate non-file fields first foreach ($postFields as $name => $content) { $data .= "--" . $delimiter . "\r\n"; $data .= 'Content-Disposition: form-data; name="' . $name . '"'; $data .= "\r\n\r\n"; } // Populate file fields foreach ($fileFields as $name => $file) { $data .= "--" . $delimiter . "\r\n"; $data .= 'Content-Disposition: form-data; name="' . $name . '";' . ' filename="' . $name . '"' . "\r\n"; $data .= 'Content-Type: ' . $file['type'] . "\r\n"; $data .= "\r\n"; $data .= $file['content'] . "\r\n"; } // Last delimiter $data .= "--" . $delimiter . "--\r\n"; $handle = curl_init($url); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_HTTPHEADER , array( 'Content-Type: multipart/form-data; boundary=' . $delimiter, 'Content-Length: ' . strlen($data))); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); curl_exec($handle);</code>
By following these steps, we can construct multipart form data with file content strings and submit it using cURL, eliminating the need for temporary file creation. This approach grants developers greater control and flexibility in handling file uploads within their PHP applications.
Atas ialah kandungan terperinci Bolehkah Anda Menghantar Rentetan Kandungan Fail Terus Menggunakan cURL Tanpa Membuat Fail Sementara?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!