| 特性 | multipart/form-data | application/x-www-form-urlencoded |
|---|---|---|
| Content-Type | multipart/form-data; boundary=----WebKitFormBoundary... | application/x-www-form-urlencoded |
| 資料編碼 | 每欄位獨立 Part,含 Header+Body,支援二進位檔案 | 鍵值對 URL 編碼 key1=val1&key2=val2 |
| 檔案上傳 | ✅ 原生支援 | ❌ 不支援 (需 Base64 編碼放入欄位) |
| PHP cURL 預設 | **陣列傳給 CURLOPT_POSTFIELDS 時自動使用** | 需手動 http_build_query() + 設定 Header |
| 適用場景 | 檔案上傳、混合表單、非 ASCII 資料 | 純文字鍵值對、API 呼叫、傳統表單提交 |
| 伺服端解析 | PHP $_FILES + $_POST | PHP $_POST (自動解析) |
<?php
function postMultipart(string $url, array $fields, array $files = [], array $options = []): string {
$ch = curl_init();
// 處理檔案上傳:CURLFile 物件 (PHP 5.5+)
$postData = $fields;
foreach ($files as $key => $path) {
if (!is_file($path)) throw new \InvalidArgumentException("File not found: $path");
$mime = mime_content_type($path) ?: 'application/octet-stream';
$postData[$key] = new CURLFile($path, $mime, basename($path));
}
$defaultOptions = [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData, // 陣列含 CURLFile → 自動 multipart
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => true, // 生產環境必須 true
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'PHP-cURL/'.phpversion(),
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_HEADER => false,
];
curl_setopt_array($ch, $defaultOptions + $options);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($errno) throw new \RuntimeException("cURL error ($errno): $error");
if ($info['http_code'] >= 400) throw new \RuntimeException("HTTP {$info['http_code']}");
return $response;
}
// 使用範例:上傳頭像
$response = postMultipart(
'https://api.example.com/upload',
['user_id' => 123, 'description' => 'avatar'],
['avatar' => '/tmp/avatar.png']
);
<?php
function postFormUrlEncoded(string $url, array $data, array $options = []): string {
$ch = curl_init();
$defaultOptions = [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($data), // 關鍵:陣列轉查詢字串
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'PHP-cURL/'.phpversion(),
CURLOPT_TIMEOUT => 30,
];
curl_setopt_array($ch, $defaultOptions + $options);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($errno) throw new \RuntimeException("cURL error ($errno): $error");
if ($info['http_code'] >= 400) throw new \RuntimeException("HTTP {$info['http_code']}");
return $response;
}
// 使用範例:OAuth2 取得 token
$tokenResponse = postFormUrlEncoded(
'https://auth.example.com/oauth/token',
[
'grant_type' => 'client_credentials',
'client_id' => 'my_client_id',
'client_secret' => 'super_secret',
'scope' => 'read write',
]
);
$tokenData = json_decode($tokenResponse, true);
cURL 內部邏輯:CURLOPT_POSTFIELDS 接收**陣列** → 自動構建 multipart/form-data;接收**字串** → 直接發送字串內容,**不自動加 Header**。
<?php
$data = ['arr' => [1,2,3], 'obj' => (object)['a'=>1]];
// PHP 5.3+ 預設使用 PHP_QUERY_RFC3986 (RFC 3986 標準編碼)
// 空格編碼為 %20 (非 +)
// 巢狀陣列編碼為 arr[0]=1&arr[1]=2&arr[2]=3
// 物件轉為陣列後編碼
echo http_build_query($data);
// arr%5B0%5D=1&arr%5B1%5D=2&arr%5B2%5D=3&obj%5Ba%5D=1
<?php
// ❌ PHP 5.5 前舊寫法:@ 開頭路徑
$postData['file'] = '@/path/to/file.png'; // 僅在 CURLOPT_SAFE_UPLOAD=false 時生效
// ✅ 現代寫法:CURLFile 物件
$postData['file'] = new CURLFile('/path/to/file.png', 'image/png', 'file.png');
// ⚠️ 關閉舊式上傳 (PHP 5.6+ 預設關閉)
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); // 預設 true,防止 @ 註入攻擊
multipart 請求會自動生成隨機 boundary,分隔各 Part。伺服端解析器依據 boundary 切分。無需手動設定。
| 現象 | 原因 | 解決 |
|---|---|---|
| $_POST 為空、$_FILES 為空 | Content-Type 錯誤或未設定 | 檢查 CURLOPT_HTTPHEADER、確認 http_build_query vs 陣列 |
| 檔案上傳失敗 400/500 | CURLFile 路徑錯誤、MIME 類型不支援、檔案過大 | 驗證 is_file()、filesize()、伺服端上傳限制 |
| 中文亂碼 | 編碼不一致 | 確保檔案 UTF-8、http_build_query 預設 UTF-8、Header charset=utf-8 |
| SSL 憑證驗證失敗 | CA 憑證缺失 | 設定 CURLOPT_CAINFO 指向 cacert.pem |
| 超時 | 網路/伺服端慢 | 調大 CURLOPT_TIMEOUT/CURLOPT_CONNECTTIMEOUT |
<?php
class HttpClient {
private $ch;
public function __construct() {
$this->ch = curl_init();
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'MyApp/1.0 (PHP-cURL)',
CURLOPT_TIMEOUT => 30,
]);
}
public function request(string $method, string $url, array $data = [], array $headers = [], bool $multipart = false): array {
$opts = [CURLOPT_URL => $url, CURLOPT_CUSTOMREQUEST => strtoupper($method)];
if ($multipart) {
// 檔案欄位自動轉 CURLFile
foreach ($data as $k => $v) {
if ($v instanceof \SplFileInfo) {
$data[$k] = new \CURLFile($v->getRealPath(), $v->getMimeType(), $v->getFilename());
}
}
$opts[CURLOPT_POSTFIELDS] = $data;
} elseif (in_array($method, ['POST', 'PUT', 'PATCH'])) {
$opts[CURLOPT_POSTFIELDS] = http_build_query($data);
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
}
if ($headers) $opts[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array($this->ch, $opts);
$response = curl_exec($this->ch);
$info = curl_getinfo($this->ch);
if (curl_errno($this->ch)) {
throw new \RuntimeException(curl_error($this->ch), curl_errno($this->ch));
}
return [
'status' => $info['http_code'],
'headers' => $this->parseHeaders($info['header_size'] ?? 0),
'body' => $response,
'json' => json_decode($response, true),
];
}
private function parseHeaders(int $headerSize): array { /* 解析回應 Header */ return []; }
public function __destruct() { curl_close($this->ch); }
}
// 使用
$client = new HttpClient();
$res = $client->request('POST', 'https://api.example.com/users', ['name' => 'Tom']);
$res = $client->request('POST', 'https://api.example.com/upload', ['file' => new SplFileInfo('/tmp/a.png')], [], true);
http_build_query + Header)。Content-Type: application/json + json_encode。CURLOPT_CAINFO。