使用 cURL 發送 POST 請求,支援 HTTPS、Cookie 管理、自訂標頭、超時控制。
<?php
function post($url, $params = false, $header = array()) {
$ch = curl_init();
$cookieFile = 'cookie_jar.txt';
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 開發環境關閉驗證
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');
if ($params !== false) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// 使用範例:微信二維碼 API
$QRCode_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $ACC_TOKEN;
$data = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}';
$header = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
);
$result = post($QRCode_URL, $data, $header);
?>
CURLOPT_RETURNTRANSFER:回傳字串而非直接輸出CURLOPT_SSL_VERIFYPEER:生產環境建議設為 true 並配置 CA 憑證CURLOPT_COOKIEJAR/FILE:自動管理 Session CookieCURLOPT_FOLLOWLOCATION:自動追蹤 301/302 重導向CURLOPT_POSTFIELDS:陣列會以 multipart/form-data 送出,字串則為 application/x-www-form-urlencoded$result = curl_exec($ch);
if ($result === false) {
$error = curl_error($ch);
$errno = curl_errno($ch);
// 記錄錯誤日誌
}
curl_close($ch);