首頁  >  文章  >  後端開發  >  如何在沒有臨時檔案的情況下在 PHP 中使用 cURL 發布檔案字串?

如何在沒有臨時檔案的情況下在 PHP 中使用 cURL 發布檔案字串?

Susan Sarandon
Susan Sarandon原創
2024-10-17 18:30:02232瀏覽

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

在PHP 中使用cURL 發布文件字串

當文件僅表示為字串時,將文件與其他表單資料一起發送的任務變得更加複雜。本教學課程示範如何在 PHP 中使用 cURL 建置請求並繞過臨時檔案建立。

解決方案

分析來自瀏覽器的範例 POST 請求,揭示了一個 multipart/form-data 結構,其中包含獨特的邊界。手動複製此格式涉及:

  1. 建立表單資料正文:分隔檔案和非檔案字段,並將它們與適當的標題和分隔符號連接起來。範例:
--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. 設定 cURL 選項: 設定 cURL 以處理帶有 multipart/form-data 的 POST 要求並指定內容長度。
<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. 執行cURL要求:使用curl_setopt設定POST欄位並執行要求。
<code class="php">curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);</code>

透過製作body和設定適當的標頭,我們模擬來自瀏覽器的 POST 請求並避免建立臨時檔案。

以上是如何在沒有臨時檔案的情況下在 PHP 中使用 cURL 發布檔案字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn