cURL 支援多種協定(HTTP/HTTPS/FTP...)、認證、Cookie、代理、檔案上傳,功能遠超 file_get_contents。本文以最基礎的「模擬 POST 登入驗證」為例,展示 cURL 核心流程:初始化 → 設定選項 → 執行 → 關閉,並對照驗證端代碼說明交互細節。
<?php
header('Content-Type: text/html; charset=utf-8');
$user = 'lee';
$pass = '123456';
$url = 'https://localhost/validate.php';
$post = "loginname=$user&loginpass=$pass";
$ch = curl_init(); // 1. 初始化
curl_setopt($ch, CURLOPT_URL, $url); // 2. 目標 URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // 0=直接輸出, 1=回傳字串
curl_setopt($ch, CURLOPT_POST, 1); // 3. POST 模式
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // 4. POST 資料
$data = curl_exec($ch); // 5. 執行
curl_close($ch); // 6. 關閉
<?php
header('Content-Type: text/html; charset=utf-8');
if ($_POST['loginname'] == 'lee' && $_POST['loginpass'] == '123456') {
echo '<script>alert("登入成功!");</script>';
} else {
echo '<script>alert("登入失敗!");</script>';
}
| 選項 | 值 | 說明 |
|---|---|---|
| CURLOPT_URL | 字串 | 請求目標網址 |
| CURLOPT_RETURNTRANSFER | 0/1 | 1 時 curl_exec 回傳字串,0 直接輸出 |
| CURLOPT_POST | 1 | 啟用 POST |
| CURLOPT_POSTFIELDS | 字串/陣列 | POST 資料,陣列自動編碼為 multipart/form-data |
| CURLOPT_COOKIEJAR | 檔案路徑 | 回應 Cookie 儲存檔案(登入維持 Session 必備) |
| CURLOPT_COOKIEFILE | 檔案路徑 | 請求前讀取 Cookie 檔案 |
| CURLOPT_SSL_VERIFYPEER | 0/1 | 驗證 SSL 憑證,測試可設 0 |
charset=utf-8,POST 資料以 urlencode() 編碼。allow_url_fopen、DNS 解析。CURLOPT_FOLLOWLOCATION, 1。下一篇將介紹:Cookie 持久化模擬真實登入狀態、GET 請求攜帶參數、檔案上傳(multipart/form-data)、JSON API 對接、並發請求與超時控制。