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

PHP cURL 實作 GET 與 POST 請求完整教學

     編輯:PHP 綜合知識

PHP cURL 基礎與實戰

cURL 是 PHP 中最強大的 HTTP 客端端庫,支援多種協定。掌握四步驟核心流程:初始化 → 設定選項 → 執行 → 關閉。

核心四步驟

  1. curl_init() 初始化會話
  2. curl_setopt() 設定 URL、標頭、POST 資料等
  3. curl_exec() 執行並取得回應
  4. curl_close() 釋放資源

GET 請求範例

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/users');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 回傳字串而非直接輸出
curl_setopt($ch, CURLOPT_HEADER, false);        // 不包含回應標頭

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo '錯誤: ' . curl_error($ch);
} else {
    $data = json_decode($response, true); // 轉為關聯陣列
    print_r($data);
}

curl_close($ch);
?>

POST 請求範例(表單格式)

<?php
$url = 'https://api.example.com/login';
$postData = [
    'username' => 'admin',
    'password' => 'secret123'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 表單格式

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
if ($result['success']) {
    echo '登入成功,Token: ' . $result['token'];
}
?>

POST JSON 資料(API 常用)

<?php
$jsonData = json_encode(['user_id' => 123, 'action' => 'update']);
$ch = curl_init('https://api.example.com/action');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData)
]);
$response = curl_exec($ch);
curl_close($ch);
?>

常用選項速查表

選項說明
CURLOPT_TIMEOUT最大執行秒數
CURLOPT_CONNECTTIMEOUT連線逾時秒數
CURLOPT_SSL_VERIFYPEER驗證 SSL 憑證(測試可設 false)
CURLOPT_FOLLOWLOCATION自動追蹤 3xx 重導向
CURLOPT_USERAGENT自訂 User-Agent

錯誤處理最佳實踐

<?php
function curlRequest($url, $options = []) {
    $ch = curl_init($url);
    curl_setopt_array($ch, $options + [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    ]);
    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    if ($errno) {
        throw new Exception("cURL 錯誤 [$errno]: $error");
    }
    if ($info['http_code'] >= 400) {
        throw new Exception("HTTP 錯誤 {$info['http_code']}: $response");
    }
    return $response;
}
?>

封裝成函式或類別可大幅提升維護性,生產環境建議加入重試機制、日誌記錄與熔斷器模式。

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