cURL(Client URL Library)是一个用于传输数据的库和命令行工具,支持多种协议(HTTP、HTTPS、FTP等)。在PHP中,我们可以使用cURL扩展来发送HTTP请求并与远程服务器交互。
<?php
// 初始化cURL会话
$ch = curl_init();
// 设置URL和其他选项
curl_setopt($ch, CURLOPT_URL, "https://example.com/api");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应保存到变量而不直接输出
curl_setopt($ch, CURLOPT_HEADER, false); // 不包含响应头
// 执行请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if(curl_errno($ch)){
echo 'cURL错误: ' . curl_error($ch);
}
// 关闭cURL会话
curl_close($ch);
// 处理响应
echo $response;
?>
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api?param1=value1¶m2=value2");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = [
'username' => 'user1',
'password' => 'pass123'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/login");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = [
'name' => 'John Doe',
'email' => 'john@example.com'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/users");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer token123'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// 跳过SSL验证(仅用于测试环境)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 设置超时时间(秒)
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 自动跟随重定向
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// 设置最大重定向次数
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
function sendRequest($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_HEADER, false);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
} elseif ($method === 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: $error");
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'status' => $httpCode,
'body' => $response
];
}
通过以上方法和示例,您可以在PHP中有效地使用cURL进行各种HTTP请求操作。
没有搜到相关的文章