在 PHP 中,cURL 是一个强大的库,用于与各种服务器进行通信(支持 HTTP、HTTPS、FTP 等协议)。以下是 cURL 的详细实现步骤和示例代码:
基本使用步骤
初始化会话:curl_init()
设置选项:curl_setopt()
执行请求:curl_exec()
关闭会话:curl_close()
错误处理:curl_errno(), curl_error()
GET 请求示例
// 1. 初始化 cURL 会话
$ch = curl_init();
// 2. 设置请求 URL
$url = "https://jsonplaceholder.typicode.com/posts/1";
curl_setopt($ch, CURLOPT_URL, $url);
// 3. 设置返回响应而非直接输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 4. 可选:设置超时时间(秒)
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// 5. 执行请求并获取响应
$response = curl_exec($ch);
// 6. 检查错误
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch);
} else {
// 处理响应(例如 JSON 解析)
$data = json_decode($response, true);
print_r($data);
}
// 7. 关闭会话
curl_close($ch);
?>
POST 请求示例
$ch = curl_init();
$url = "https://jsonplaceholder.typicode.com/posts";
// POST 数据(表单格式)
$postData = [
'title' => 'Test Post',
'body' => 'This is a test post.',
'userId' => 1
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true); // 启用 POST
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 编码数据
// 设置请求头(可选)
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
echo "Response: " . $response;
}
curl_close($ch);
?>
高级选项设置
1. 设置请求头
$headers = [
'Authorization: Bearer YOUR_ACCESS_TOKEN',
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
2. 发送 JSON 数据
$jsonData = json_encode(['key' => 'value']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
3. 获取响应头信息
curl_setopt($ch, CURLOPT_HEADER, true); // 包含响应头
$response = curl_exec($ch);
// 分离头部和主体
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
4. 处理 HTTPS 证书
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不验证证书(测试环境)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
5. 跟随重定向
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 自动跟随重定向
curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // 最大重定向次数
调试与错误处理
// 获取 HTTP 状态码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "Status Code: " . $httpCode;
// 获取请求总时间
$totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
echo "Request Time: " . $totalTime . " seconds";
完整封装函数示例
function curlRequest($url, $method = 'GET', $data = null, $headers = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$response = curl_exec($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'code' => $httpCode,
'response' => $response,
'error' => $error
];
}
// 使用示例
$result = curlRequest(
'https://api.example.com/data',
'POST',
json_encode(['param' => 'value']),
['Content-Type: application/json']
);
print_r($result);
常见问题解决
请求超时:增加 CURLOPT_TIMEOUT 值。
SSL 证书错误:
正式环境:下载 CA 证书并设置 CURLOPT_CAINFO。
测试环境:临时禁用验证(不推荐生产环境使用)。
返回乱码:
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate'); // 自动解压
通过以上示例,你可以快速实现 GET/POST 请求、处理 JSON 数据、设置请求头和调试错误。根据实际需求调整参数即可。