Google 等大型網站對無 Cookie 的請求會回傳連續 302 重導向,導致無法取得實際內容。模擬瀏覽器行為:先 GET 首頁建立 Cookie → 再攜帶 Cookie 發送搜尋請求。
<?php
header('Content-Type: text/html; charset=utf-8');
$cookie_file = __DIR__ . '/cookie.txt'; // 固定檔案路徑,便於除錯
// ---------- 階段 1:取得 Cookie ----------
$url = 'https://www.google.com.hk';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); // 儲存 Cookie
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 開發環境跳過憑證驗證
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 自動追蹤重導向
curl_exec($ch);
curl_close($ch);
// ---------- 階段 2:攜帶 Cookie 搜尋 ----------
$search_url = 'https://www.google.com.hk/search?oe=utf8&ie=utf8&source=uds&hl=zh-CN&q=php+curl';
$ch = curl_init($search_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); // 讀取 Cookie
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
| 參數 | 說明 |
|---|---|
| CURLOPT_COOKIEJAR | 寫入 Cookie 的檔案(登入/首次訪問用) |
| CURLOPT_COOKIEFILE | 讀取 Cookie 的檔案(後續請求用) |
| CURLOPT_FOLLOWLOCATION | 自動處理 301/302 重導向 |
| CURLOPT_SSL_VERIFYPEER | false 可跳過 HTTPS 憑證驗證(僅開發/測試) |
| CURLOPT_USERAGENT | 偽裝瀏覽器 UA,降低被封鎖機率 |
| CURLOPT_TIMEOUT | 設定連線逾時秒數,防止卡死 |
class CurlClient {
private $cookieFile;
private $ch;
public function __construct($cookieFile = '') {
$this->cookieFile = $cookieFile ?: sys_get_temp_dir() . '/curl_cookie_' . md5($_SERVER['HTTP_HOST']) . '.txt';
}
public function get($url, array $options = []) {
return $this->request('GET', $url, null, $options);
}
public function post($url, $data, array $options = []) {
return $this->request('POST', $url, $data, $options);
}
private function request($method, $url, $data, $options) {
$this->ch = curl_init($url);
$defaults = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_COOKIEJAR => $this->cookieFile,
CURLOPT_COOKIEFILE => $this->cookieFile,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
CURLOPT_TIMEOUT => 30,
];
curl_setopt_array($this->ch, $defaults + $options);
if ($method === 'POST') {
curl_setopt($this->ch, CURLOPT_POST, true);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
}
$resp = curl_exec($this->ch);
if (curl_errno($this->ch)) {
throw new Exception(curl_error($this->ch));
}
curl_close($this->ch);
return $resp;
}
}
CURLOPT_SSL_VERIFYPEER => true 並配置 CA 憑證束。