PHP curl库有哪些高级用法

PHP
716
2024/9/14 18:30:46
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

PHP的cURL库提供了许多高级功能,可以帮助您更好地处理HTTP请求。以下是一些常见的高级用法:

  1. 发送POST请求:
$url = "https://example.com/api";
$data = array("key" => "value");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
  1. 设置自定义请求头:
$headers = array(
    "Content-Type: application/json",
    "Authorization: Bearer YOUR_ACCESS_TOKEN"
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
  1. 上传文件:
$file = "@/path/to/your/file.jpg";
$data = array("file" => $file);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
  1. 使用代理:
$proxy = "http://proxy.example.com:8080";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
$response = curl_exec($ch);
curl_close($ch);
  1. 设置超时和连接超时:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间为30秒
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 设置连接超时时间为10秒
$response = curl_exec($ch);
curl_close($ch);
  1. 关注请求进度:
function progressCallback($downloadSize, $downloaded, $uploadSize, $uploaded) {
    echo "Downloaded: $downloaded / $downloadSize\n";
    echo "Uploaded: $uploaded / $uploadSize\n";
}

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
$response = curl_exec($ch);
curl_close($ch);

这些高级用法只是cURL库功能的一部分。您可以查阅PHP官方文档以获取更多关于cURL库的信息:https://www.php.net/manual/en/book.curl.php

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: PHP中的explode和implode怎么使用