爬蟲、API 整合、支付回調驗證常需:完整記錄請求/回應頭、處理重定向鏈、獲取最終落地 URL、分析效能指標。
<?php
function curlFetchFull($url, array $options = []) {
$defaults = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true, // 包含回應頭
CURLOPT_FOLLOWLOCATION => true, // 自動跟隨重定向
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot/1.0)',
CURLOPT_ENCODING => 'gzip,deflate', // 自動解壓
];
$ch = curl_init();
curl_setopt_array($ch, array_merge($defaults, $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");
}
// 分離頭部與主體
$headerSize = $info['header_size'];
$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
// 解析頭部為陣列
$headerLines = explode("\r\n", trim($headers));
$headerArray = [];
foreach ($headerLines as $line) {
if (strpos($line, ':') !== false) {
list($k, $v) = explode(':', $line, 2);
$headerArray[trim($k)] = trim($v);
}
}
return [
'url' => $info['url'], // 最終 URL (重定向後)
'http_code' => $info['http_code'],
'headers' => $headerArray,
'raw_headers' => $headers,
'body' => $body,
'info' => $info, // 完整效能指標
'redirect_count' => $info['redirect_count'],
'redirect_url' => $info['redirect_url'] ?? null,
];
}
// 使用
try {
$result = curlFetchFull('https://httpbin.org/redirect/3');
echo "最終 URL: {$result['url']}\n";
echo "狀態碼: {$result['http_code']}\n";
echo "重定向次數: {$result['redirect_count']}\n";
print_r($result['headers']);
} catch (Exception $e) {
echo "錯誤: " . $e->getMessage();
}
?>
CURLOPT_FOLLOWLOCATION 只能拿到最終 URL,無法獲取中間重定向鏈。需手動實現:
<?php
function curlTraceRedirects($url, $maxRedirects = 10) {
$chain = [];
$currentUrl = $url;
for ($i = 0; $i < $maxRedirects; $i++) {
$ch = curl_init($currentUrl);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true, // HEAD 請求
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false, // 關鍵:不自動跟隨
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_USERAGENT => 'RedirectTracer/1.0'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
curl_close($ch);
$chain[] = [
'step' => $i + 1,
'url' => $currentUrl,
'http_code' => $httpCode,
'headers' => $headers
];
// 檢查是否重定向
if (in_array($httpCode, [301, 302, 303, 307, 308])) {
if (preg_match('/Location:\s*(.+)/i', $headers, $matches)) {
$nextUrl = trim($matches[1]);
// 處理相對 URL
$currentUrl = parse_url($nextUrl, PHP_URL_SCHEME) ? $nextUrl :
rtrim($currentUrl, '/') . '/' . ltrim($nextUrl, '/');
continue;
}
}
break; // 非重定向或無 Location,結束
}
return $chain;
}
// 測試
$chain = curlTraceRedirects('https://httpbin.org/redirect/3');
foreach ($chain as $step) {
echo "Step {$step['step']}: {$step['url']} -> {$step['http_code']}\n";
}
/*
Step 1: https://httpbin.org/redirect/3 -> 302
Step 2: https://httpbin.org/relative-redirect/2 -> 302
Step 3: https://httpbin.org/relative-redirect/1 -> 302
Step 4: https://httpbin.org/get -> 200
*/
$info = curl_getinfo($ch);
/*
關鍵指標:
'url' => 最終有效 URL
'content_type' => Content-Type
'http_code' => HTTP 狀態碼
'header_size' => 回應頭大小
'request_size' => 請求大小
'filetime' => 文件時間 (-1 表未知)
'ssl_verify_result'=> SSL 驗證結果
'redirect_count' => 重定向次數
'total_time' => 總耗時 (秒)
'namelookup_time' => DNS 解析耗時
'connect_time' => TCP 連線耗時
'pretransfer_time' => 握手/準備傳輸耗時
'starttransfer_time'=> 首字節時間 (TTFB)
'redirect_time' => 重定向總耗時
'speed_download' => 下載速度 (bytes/sec)
'speed_upload' => 上傳速度
'download_content_length' => Content-Length
'upload_content_length' => 請求體大小
'primary_ip' => 解析後 IP
'primary_port' => 端口
'local_ip' => 本地 IP
'local_port' => 本地端口
*/
<?php
// 支付寶/微信回調驗證:需原始 POST 資料 + 簽名驗證
$rawPost = file_get_contents('php://input'); // 獲取原始 Body
$headers = getallheaders(); // 獲取所有請求頭
// 使用 cURL 向支付網關驗證 (以支付寶為例)
function verifyAlipayNotify($params) {
$ch = curl_init('https://openapi.alipay.com/gateway.do');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'method' => 'alipay.trade.query',
'app_id' => $config['app_id'],
'charset' => 'utf-8',
'sign_type' => 'RSA2',
'timestamp' => date('Y-m-d H:i:s'),
'version' => '1.0',
'biz_content' => json_encode(['out_trade_no' => $params['out_trade_no']]),
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_CAINFO => __DIR__ . '/cacert.pem', // 支付寶公鑰證書
CURLOPT_TIMEOUT => 15,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode === 200 && json_decode($response, true)['code'] === '10000';
}
<?php
function curlDebug($url, $postData = null) {
$verbose = fopen('php://temp', 'rw+');
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true,
CURLOPT_STDERR => $verbose, // 將詳細輸出導向流
CURLOPT_HEADER => true,
CURLOPT_TIMEOUT => 10,
]);
if ($postData) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
fclose($verbose);
// 解析 verbose log 可見完整請求/回應頭、SSL 握手細節
return ['response' => $response, 'info' => $info, 'verbose' => $verboseLog];
}
CURLOPT_FOLLOWLOCATION + curl_getinfo()['url'] 獲取最終 URLcurl_getinfo() 提供完整時間細分,定位瓶頸 (DNS/連線/TTFB/下載)