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

PHP cURL 入門實戰:Cookie 登入驗證、憑證部署、多環境編譯指南

     編輯:PHP 綜合知識

基本登入流程範例

<?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;
?>

Windows 環境部署 cURL

  1. `php.ini` 取消註解:`extension=php_curl.dll`
  2. 將 PHP 目錄下的 `libeay32.dll`、`ssleay32.dll` (PHP 7 為 `libcrypto-1_1.dll`、`libssl-1_1.dll`) 複製到 `C:\Windows\System32`
  3. 重啟 Apache/IIS,`phpinfo()` 搜尋 `cURL support enabled`

Linux 環境編譯 PHP 含 cURL

# 安裝 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

常用 cURL 選項速查

選項用途
CURLOPT_URL請求網址
CURLOPT_POST1=POST 請求
CURLOPT_POSTFIELDSPOST 資料(陣列或字串)
CURLOPT_COOKIEJAR回應 Cookie 存檔路徑
CURLOPT_COOKIEFILE請求攜帶 Cookie 檔案
CURLOPT_RETURNTRANSFER1=回傳字串,0=直接輸出
CURLOPT_HEADER1=包含回應標頭
CURLOPT_NOBODY1=僅 HEAD 請求
CURLOPT_TIMEOUT總超時秒數
CURLOPT_CONNECTTIMEOUT連線階段超時秒數
CURLOPT_SSL_VERIFYPEER驗證 SSL 憑證(生產建議 1)
CURLOPT_FOLLOWLOCATION自動跟隨重導向
CURLOPT_MAXREDIRS最大重導向次數
CURLOPT_USERAGENT自定 User-Agent

進階技巧

  • 並發請求:`curl_multi_init()` 批次處理多個 handle,大幅降低總耗時。
  • 斷點續傳:`CURLOPT_RESUME_FROM` 指定起始位元組。
  • 上傳檔案:`CURLOPT_POSTFIELDS` 陣列中鍵值為 `@/path/to/file` (PHP 5.5+ 建議用 `CURLFile` 類別)。
  • 代理穿透:`CURLOPT_PROXY`、`CURLOPT_PROXYUSERPWD`。

cURL 是 PHP 後端網路通訊的瑞士刀,熟練掌握可解決 90% 以上對外整合需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved