php.ini,移除 ;extension=php_curl.dll 前的分號。libeay32.dll、ssleay32.dll、php5ts.dll 複製至系統目錄(如 C:\Windows)。phpinfo() 確認 cURL 區塊出現。<?php
class Curl {
public $cookieFile;
public $timeout = 160;
public function __construct($dir = '') {
$this->cookieFile = $this->getTemporaryCookieFileName($dir);
}
/** 發送請求並返回回應字串 */
public function getResponseText(array $curlOptions) {
// 強制返回字串
$curlOptions[CURLOPT_RETURNTRANSFER] = true;
$curl = curl_init();
curl_setopt_array($curl, $curlOptions);
$responseText = '';
try {
$responseText = curl_exec($curl);
if (($errno = curl_errno($curl)) !== CURLE_OK) {
throw new Exception(curl_error($curl), $errno);
}
} catch (Exception $e) {
$responseText = false;
} finally {
curl_close($curl);
}
return $responseText;
}
/** Unicode \uXXXX 轉 UTF-8 */
public function unicodeToUtf8($string) {
$string = str_replace('u', '', strtolower($string));
$len = strlen($string) / 4;
$result = '';
for ($i = 0; $i < $len; $i++) {
$hex = substr($string, $i * 4, 4);
$code = hexdec($hex);
if ($code < 128) {
$result .= chr($code);
} elseif ($code < 2048) {
$result .= chr(192 + (($code - 64) / 64)) . chr(128 + ($code % 64));
} else {
$result .= chr(224 + (($code - 4096) / 4096))
. chr(128 + ((($code % 4096) - 64) / 64))
. chr(128 + ($code % 64));
}
}
return $result;
}
private function getTemporaryCookieFileName($dir = '.') {
return str_replace('\\', '/', tempnam($dir, 'tmp'));
}
}
require_once 'curl.class.php';
$curl = new Curl();
$options = [
CURLOPT_URL => 'https://www.example.com/api',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_REFERER => 'https://www.example.com',
CURLOPT_HTTPHEADER => [
'X-FORWARDED-FOR: 139.197.14.19',
'CLIENT-IP: 127.0.0.1'
],
CURLOPT_HEADER => 1,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => 'ids=897&Submit=%E6%8A%95%E7%A5%A8',
CURLOPT_TIMEOUT => $curl->timeout,
];
$response = $curl->getResponseText($options);
var_dump($response);
另一種常見封裝採用靜態 create() 建立 cURL handle,再鏈式設定選項:
class Curl {
static function create() { return curl_init(); }
function execute($method, $url, $fields = '', $userAgent = '', $headers = '', $user = '', $pass = '') {
$ch = self::create();
if (!$ch || !$url) return false;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($user) curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
$method = strtolower($method);
if ($method === 'post') {
curl_setopt($ch, CURLOPT_POST, true);
if (is_array($fields)) {
$fields = http_build_query($fields);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
} elseif ($method === 'put') {
curl_setopt($ch, CURLOPT_PUT, true);
}
if ($userAgent) curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
if (is_array($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
return curl_exec($ch);
}
}
CURLOPT_SSL_VERIFYPEER => true)。CURLOPT_TIMEOUT 與 CURLOPT_CONNECTTIMEOUT 避免阻塞。