cURL (Client URL Library) 是一个用于传输数据的库和命令行工具,支持多种协议(HTTP、HTTPS、FTP等)。在PHP中,cURL扩展提供了与各种服务器通信的功能。
<?php
// 初始化cURL会话
$ch = curl_init();
// 设置请求URL
$url = "https://example.com/api";
curl_setopt($ch, CURLOPT_URL, $url);
// 设置为POST请求
curl_setopt($ch, CURLOPT_POST, true);
// 设置POST数据
$postData = [
'username' => 'user123',
'password' => 'pass456'
];
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
// 设置返回响应而不是直接输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 执行请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if(curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch);
}
// 获取HTTP状态码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "HTTP Code: " . $httpCode . "\n";
// 关闭cURL会话
curl_close($ch);
// 输出响应
echo "Response: " . $response;
?>
<?php
$ch = curl_init();
$url = "https://example.com/api/json";
$data = json_encode([
'name' => 'John Doe',
'email' => 'john@example.com'
]);
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
]
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
// 假设响应是JSON格式
$decodedResponse = json_decode($response, true);
print_r($decodedResponse);
}
curl_close($ch);
?>
原因:服务器SSL证书无效或自签名
解决方案:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不验证对等证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
注意:生产环境中应避免禁用SSL验证,应正确配置CA证书
解决方案:
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 30秒超时
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 10秒连接超时
curl_setopt($ch, CURLOPT_HEADER, true); // 包含头信息在输出中
// 执行后分离头和主体
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向
curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // 最大重定向次数
// 创建多个cURL句柄
$mh = curl_multi_init();
$handles = [];
for ($i = 0; $i < 5; $i++) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api?page=".$i);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
// 执行批处理
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running > 0);
// 获取结果
foreach ($handles as $ch) {
$response = curl_multi_getcontent($ch);
echo $response;
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
$file = '/path/to/file.jpg';
$postData = [
'file' => new CURLFile($file, 'image/jpeg', 'upload.jpg'),
'description' => 'Sample file upload'
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://example.com/upload',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
// 处理响应...
通过以上方法和示例,您可以有效地在PHP中使用cURL进行POST请求并处理响应结果。