curl_init() 初始化會話curl_setopt() 設定選項curl_exec() 執行請求curl_close() 關閉釋放資源
$curlPost = 'a=1&b=2'; // POST 資料
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-FORWARDED-FOR: 0.0.0.0',
'CLIENT-IP: 0.0.0.0'
]); // 偽造來源 IP (視伺服器端是否信任此 Header)
curl_setopt($ch, CURLOPT_REFERER, "https://www.jb51.net/"); // 偽造 Referer
curl_setopt($ch, CURLOPT_URL, 'https://www.jb51.net'); // 目標 URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 返回字串而非直接輸出
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 總超時秒數
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); // POST 資料
$file_contents = curl_exec($ch); // 執行並取得內容
curl_close($ch);
echo $file_contents;
| 選項 | 說明 | 典型值 |
|---|---|---|
CURLOPT_URL | 請求網址 | 'https://api.example.com' |
CURLOPT_RETURNTRANSFER | 返回字串而非直接輸出 | true / 1 |
CURLOPT_POST | 啟用 POST | true |
CURLOPT_POSTFIELDS | POST 資料 (字串或陣列) | 'a=1&b=2' / ['a'=>1,'b'=>2] |
CURLOPT_HTTPHEADER | 自定 Header 陣列 | ['Authorization: Bearer xxx', 'Content-Type: application/json'] |
CURLOPT_REFERER | Referer 標頭 | 'https://referer.com' |
CURLOPT_USERAGENT | User-Agent | 'Mozilla/5.0...' |
CURLOPT_TIMEOUT | 總超時 (秒) | 30 |
CURLOPT_CONNECTTIMEOUT | 連線超時 (秒) | 10 |
CURLOPT_FOLLOWLOCATION | 跟隨 3xx 重導向 | true |
CURLOPT_MAXREDIRS | 最大重導向次數 | 5 |
CURLOPT_SSL_VERIFYPEER | 驗證 SSL 憑證 | false (開發/測試), true (生產) |
CURLOPT_COOKIEJAR/FILE | Cookie 儲存/載入檔案 | 'cookies.txt' |
CURLOPT_ENCODING | 接受編碼 (gzip/deflate) | 'gzip,deflate' |
$data = ['user' => 'admin', 'pass' => 'secret'];
$json = json_encode($data);
$ch = curl_init('https://api.example.com/login');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Content-Length: ' . strlen($json),
'Accept: application/json'
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
]);
$resp = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
$result = json_decode($resp, true);
// 處理 $result
}
$resp = curl_exec($ch);
if ($resp === false) {
$errno = curl_errno($ch);
$error = curl_error($ch);
// 記錄錯誤: $errno, $error
throw new Exception("cURL error ($errno): $error");
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode < 200 || $httpCode >= 300) {
throw new Exception("HTTP $httpCode: $resp");
}
cURL 是 PHP 伺服器端 HTTP 客戶端的標準選擇。掌握 curl_setopt_array 批量設定、CURLOPT_RETURNTRANSFER 獲取回應、CURLOPT_TIMEOUT 防止掛住、CURLOPT_SSL_VERIFYPEER 安全控制、錯誤碼/HTTP 狀態碼雙重檢查,即可構建健壯的資料抓取/整合功能。