首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP cURL 取得 Cookie 模擬登入 Google 搜尋實戰

     編輯:PHP 相關知識

背景:為何需要先取得 Cookie?

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_VERIFYPEERfalse 可跳過 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;
    }
}

實務提醒

  • Google 等網站有反爬蟲機制(驗證碼、IP 限流),大量抓取請使用官方 API(Custom Search JSON API)。
  • Cookie 檔案需定期清理,避免過期 Cookie 導致請求異常。
  • 生產環境請啟用 CURLOPT_SSL_VERIFYPEER => true 並配置 CA 憑證束。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved