<?php
print_r($_POST);
print_r($_FILES);
?>
$file = realpath('test.jpg'); // 實體檔案必須存在
$fields['f'] = '@' . $file; // @ 開頭表示檔案上傳
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://localhost/upload.php',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_RETURNTRANSFER => true,
]);
$content = curl_exec($ch);
echo $content;
curl_close($ch);
注意:PHP 5.6+ 已棄用 @ 語法,PHP 7.0+ 移除,建議改用 CURLFile。
$file = new CURLFile(realpath('test.jpg'), 'image/jpeg', 'test.jpg');
$fields['f'] = $file;
// 其餘同上
適用於記憶體中產生的圖片、CSV、PDF 等動態內容,避免寫入暫存檔。
$contents = "這裡是檔案內容,也可以是圖片二進制資料";
$varname = 'my'; // $_FILES['my']
$filename = '3.txt'; // 檔名
$mime = 'text/plain'; // MIME 類型
// 手動構造 multipart/form-data 內容
$key = "$varname\"; filename=\"$filename\r\nContent-Type: $mime\r\n";
$fields[$key] = $contents;
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://localhost/upload.php',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_RETURNTRANSFER => true,
]);
$content = curl_exec($ch);
echo $content;
curl_close($ch);
Array
(
[my] => Array
(
[name] => 3.txt
[type] => text/plain
[tmp_name] => /tmp/phpXXXXXX
[error] => 0
[size] => 123
)
)
| 場景 | 推薦方式 |
|---|---|
| 本地現有檔案 | new CURLFile($path, $mime, $name) |
| 動態產生內容(記憶體) | 手動構造 multipart 字串(方法三) |
| 大檔案串流上傳 | CURLOPT_READFUNCTION + 檔案控制代碼 |
| 多檔案上傳 | $fields 多個 key,各自對應 CURLFile |
CURLOPT_POSTFIELDS 傳入陣列時,cURL 自動設定 Content-Type: multipart/form-data;若傳入字串則為 application/x-www-form-urlencoded。rawurlencode() 或確保系統編碼一致。upload_max_filesize、post_max_size、memory_limit、max_execution_time。