<?php
$cookieJar = tempnam('./tmp', 'cookie'); // 建立暫存 Cookie 檔
// 1. 登入 POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '登入頁面URL');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username=xxx&pwd=xxx');
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieJar); // 儲存回應 Cookie
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_exec($ch);
curl_close($ch);
// 2. 攜帶 Cookie 訪問受保護頁面
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, '受保護頁面URL');
curl_setopt($ch2, CURLOPT_COOKIEFILE, $cookieJar); // 讀取 Cookie
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_HEADER, 0);
$content = curl_exec($ch2);
curl_close($ch2);
echo $content;
?>
# 安裝 cURL 開發套件
yum install curl-devel # CentOS
apt-get install libcurl4-openssl-dev # Ubuntu
# 重新編譯 PHP
./configure \
--prefix=/usr/local/php5 \
--with-apxs2=/usr/local/apache2/bin/apxs \
--with-mysql=/usr/local/mysql \
--with-gd=/usr/local/gd \
--with-zlib --with-png --with-jpeg-dir=/usr/local/jpeg \
--with-freetype-dir=/usr/local/freetype \
--enable-sockets --with-iconv --enable-mbstring \
--with-config-file-path=/usr/local/php5/etc \
--with-curl=/usr/local/curl # 指定 cURL 安裝路徑
make && make install
| 選項 | 用途 |
|---|---|
CURLOPT_URL | 請求網址 |
CURLOPT_POST | 1=POST 請求 |
CURLOPT_POSTFIELDS | POST 資料(陣列或字串) |
CURLOPT_COOKIEJAR | 回應 Cookie 存檔路徑 |
CURLOPT_COOKIEFILE | 請求攜帶 Cookie 檔案 |
CURLOPT_RETURNTRANSFER | 1=回傳字串,0=直接輸出 |
CURLOPT_HEADER | 1=包含回應標頭 |
CURLOPT_NOBODY | 1=僅 HEAD 請求 |
CURLOPT_TIMEOUT | 總超時秒數 |
CURLOPT_CONNECTTIMEOUT | 連線階段超時秒數 |
CURLOPT_SSL_VERIFYPEER | 驗證 SSL 憑證(生產建議 1) |
CURLOPT_FOLLOWLOCATION | 自動跟隨重導向 |
CURLOPT_MAXREDIRS | 最大重導向次數 |
CURLOPT_USERAGENT | 自定 User-Agent |
cURL 是 PHP 後端網路通訊的瑞士刀,熟練掌握可解決 90% 以上對外整合需求。