In web development, transmitting files along with form data is a common requirement. While cURL offers a straightforward method to POST files from the file system, this article explores a technique to POST a file directly as a string, bypassing the need for temporary file creation.
The key lies in manually constructing the multipart/form-data request body. Begin by separating form fields from file uploads. For each non-file field, create a form-data section with the field name and value.
Next, for each file to be uploaded, create a form-data section with the file name, mime type, and actual file content.
To simulate a browser-like POST, set the appropriate headers:
<code class="php">'Content-Type: multipart/form-data; boundary=' . $delimiter 'Content-Length: ' . strlen($data)</code>
where $delimiter is a unique string that separates each section of the form data.
<code class="php">$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 constructing the multipart/form-data body and setting the necessary headers, cURL can seamlessly POST a file represented as a string, providing a more flexible and efficient approach compared to working with physical files.
以上是如何在 PHP 中使用 cURL 發布檔案字串:逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!