cURL 是 PHP 中最強大的 HTTP 客端端庫,支援多種協定。掌握四步驟核心流程:初始化 → 設定選項 → 執行 → 關閉。
curl_init() 初始化會話curl_setopt() 設定 URL、標頭、POST 資料等curl_exec() 執行並取得回應curl_close() 釋放資源<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/users');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 回傳字串而非直接輸出
curl_setopt($ch, CURLOPT_HEADER, false); // 不包含回應標頭
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo '錯誤: ' . curl_error($ch);
} else {
$data = json_decode($response, true); // 轉為關聯陣列
print_r($data);
}
curl_close($ch);
?>
<?php
$url = 'https://api.example.com/login';
$postData = [
'username' => 'admin',
'password' => 'secret123'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 表單格式
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if ($result['success']) {
echo '登入成功,Token: ' . $result['token'];
}
?>
<?php
$jsonData = json_encode(['user_id' => 123, 'action' => 'update']);
$ch = curl_init('https://api.example.com/action');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
]);
$response = curl_exec($ch);
curl_close($ch);
?>
| 選項 | 說明 |
|---|---|
| CURLOPT_TIMEOUT | 最大執行秒數 |
| CURLOPT_CONNECTTIMEOUT | 連線逾時秒數 |
| CURLOPT_SSL_VERIFYPEER | 驗證 SSL 憑證(測試可設 false) |
| CURLOPT_FOLLOWLOCATION | 自動追蹤 3xx 重導向 |
| CURLOPT_USERAGENT | 自訂 User-Agent |
<?php
function curlRequest($url, $options = []) {
$ch = curl_init($url);
curl_setopt_array($ch, $options + [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($errno) {
throw new Exception("cURL 錯誤 [$errno]: $error");
}
if ($info['http_code'] >= 400) {
throw new Exception("HTTP 錯誤 {$info['http_code']}: $response");
}
return $response;
}
?>
封裝成函式或類別可大幅提升維護性,生產環境建議加入重試機制、日誌記錄與熔斷器模式。