如何使用php curl函数

发布时间:2021-10-20 11:06:47 作者:iii
来源:亿速云 阅读:189
# 如何使用PHP cURL函数

## 目录
1. [cURL简介](#curl简介)
2. [安装与配置](#安装与配置)
3. [基本使用流程](#基本使用流程)
4. [常用cURL函数详解](#常用curl函数详解)
5. [GET请求示例](#get请求示例)
6. [POST请求示例](#post请求示例)
7. [文件上传](#文件上传)
8. [HTTP认证](#http认证)
9. [处理HTTPS请求](#处理https请求)
10. [设置请求头](#设置请求头)
11. [处理Cookie](#处理cookie)
12. [并发请求](#并发请求)
13. [错误处理](#错误处理)
14. [性能优化](#性能优化)
15. [实际应用场景](#实际应用场景)
16. [安全注意事项](#安全注意事项)
17. [常见问题解答](#常见问题解答)

<a id="curl简介"></a>
## 1. cURL简介

cURL(Client URL Library)是一个强大的开源库,支持多种协议(HTTP、HTTPS、FTP等),允许你通过URL传输数据。PHP中的cURL扩展提供了与libcurl库的接口,使PHP能够与其他服务器进行通信。

主要特点:
- 支持多种协议(HTTP/HTTPS/FTP/FTPS等)
- 支持SSL证书
- HTTP POST/PUT/DELETE等方法
- 表单提交
- 文件上传/下载
- Cookie支持
- 代理支持

<a id="安装与配置"></a>
## 2. 安装与配置

### 检查是否已安装
```php
<?php
if (!function_exists('curl_init')) {
    die('cURL扩展未安装');
}
?>

安装方法

验证安装

<?php
phpinfo();
// 搜索"cURL support"确认是否启用
?>

3. 基本使用流程

标准cURL请求流程: 1. 初始化cURL会话:curl_init() 2. 设置cURL选项:curl_setopt() 3. 执行请求:curl_exec() 4. 获取错误信息(可选):curl_error() 5. 获取请求信息(可选):curl_getinfo() 6. 关闭cURL会话:curl_close()

基本示例:

<?php
// 1. 初始化
$ch = curl_init();

// 2. 设置选项
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 3. 执行并获取结果
$output = curl_exec($ch);

// 4. 检查错误
if ($output === false) {
    echo "cURL Error: " . curl_error($ch);
}

// 5. 关闭会话
curl_close($ch);

// 处理结果
echo $output;
?>

4. 常用cURL函数详解

curl_init()

初始化一个新的cURL会话。

$ch = curl_init([string $url = null]);

curl_setopt()

设置cURL选项。

bool curl_setopt(resource $ch, int $option, mixed $value);

常用选项: - CURLOPT_URL: 请求的URL - CURLOPT_RETURNTRANSFER: 返回结果而不直接输出 - CURLOPT_POST: 启用POST请求 - CURLOPT_POSTFIELDS: POST数据 - CURLOPT_HEADER: 包含响应头 - CURLOPT_HTTPHEADER: 设置请求头 - CURLOPT_FOLLOWLOCATION: 跟随重定向 - CURLOPT_SSL_VERIFYPEER: 验证SSL证书 - CURLOPT_TIMEOUT: 超时时间(秒)

curl_exec()

执行cURL会话。

mixed curl_exec(resource $ch);

curl_close()

关闭cURL会话。

void curl_close(resource $ch);

curl_error()

返回最后一次错误的字符串。

string curl_error(resource $ch);

curl_getinfo()

获取最后一次传输的信息。

mixed curl_getinfo(resource $ch [, int $opt = 0]);

常用信息: - CURLINFO_HTTP_CODE: 最后收到的HTTP代码 - CURLINFO_TOTAL_TIME: 总传输时间 - CURLINFO_SIZE_DOWNLOAD: 下载字节数

5. GET请求示例

基本GET请求:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/api?param1=value1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

带参数的GET请求:

<?php
$params = [
    'key1' => 'value1',
    'key2' => 'value2'
];
$url = 'http://example.com/api?' . http_build_query($params);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

6. POST请求示例

基本POST请求:

<?php
$postData = [
    'username' => 'admin',
    'password' => 'secret'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/login");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

发送JSON数据:

<?php
$data = [
    'name' => 'John Doe',
    'email' => 'john@example.com'
];
$json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/api/users");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($json)
]);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

7. 文件上传

上传单个文件:

<?php
$file = new CURLFile('path/to/file.jpg', 'image/jpeg', 'file.jpg');
$postData = [
    'userfile' => $file,
    'other_field' => 'value'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/upload");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

上传多个文件:

<?php
$files = [
    'file1' => new CURLFile('path/to/file1.jpg'),
    'file2' => new CURLFile('path/to/file2.jpg')
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/multi-upload");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $files);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

8. HTTP认证

基本认证:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/protected");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

摘要认证:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/protected");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

9. 处理HTTPS请求

禁用SSL验证(不推荐生产环境使用):

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

使用CA证书验证:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CNFO, "/path/to/cacert.pem");
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

10. 设置请求头

自定义请求头:

<?php
$headers = [
    'Authorization: Bearer token123',
    'Content-Type: application/json',
    'X-Custom-Header: value'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/api");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

获取响应头:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);

curl_close($ch);

echo "Headers:\n$headers\n\nBody:\n$body";
?>

11. 处理Cookie

发送Cookie:

<?php
$cookie = "name=value; name2=value2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

保存Cookie到文件:

<?php
$cookie_file = tempnam(sys_get_temp_dir(), "cookie");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/login");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=admin&password=secret");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
$response = curl_exec($ch);
curl_close($ch);

// 后续请求使用保存的cookie
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/profile");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

12. 并发请求

使用curlmulti*函数实现并发请求:

<?php
$urls = [
    'http://example.com/api/1',
    'http://example.com/api/2',
    'http://example.com/api/3'
];

$mh = curl_multi_init();
$handles = [];

foreach ($urls as $i => $url) {
    $handles[$i] = curl_init();
    curl_setopt($handles[$i], CURLOPT_URL, $url);
    curl_setopt($handles[$i], CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($mh, $handles[$i]);
}

$running = null;
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while ($running > 0);

$results = [];
foreach ($handles as $i => $handle) {
    $results[$i] = curl_multi_getcontent($handle);
    curl_multi_remove_handle($mh, $handle);
    curl_close($handle);
}

curl_multi_close($mh);

print_r($results);
?>

13. 错误处理

基本错误处理:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://invalid.url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

if ($response === false) {
    $error = curl_error($ch);
    $errno = curl_errno($ch);
    echo "cURL Error ($errno): $error";
} else {
    echo $response;
}

curl_close($ch);
?>

获取HTTP状态码:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode !== 200) {
    echo "请求失败,HTTP状态码:$httpCode";
} else {
    echo $response;
}

curl_close($ch);
?>

14. 性能优化

  1. 复用cURL句柄: “`php <?php \(ch = curl_init(); // 第一次请求 curl_setopt(\)ch, CURLOPT_URL, “http://example.com/api1”); \(response1 = curl_exec(\)ch);

// 第二次请求(复用同一个句柄) curl_setopt(\(ch, CURLOPT_URL, "http://example.com/api2"); \)response2 = curl_exec($ch);

curl_close($ch); ?>


2. **设置合理的超时时间**:
   ```php
   curl_setopt($ch, CURLOPT_TIMEOUT, 30);        // 总超时时间
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 连接超时时间
  1. 启用Keep-Alive

    curl_setopt($ch, CURLOPT_TCP_KEEPALIVE, 1);
    curl_setopt($ch, CURLOPT_TCP_KEEPIDLE, 120);
    curl_setopt($ch, CURLOPT_TCP_KEEPINTVL, 60);
    
  2. 使用DNS缓存

    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 86400); // 24小时
    

15. 实际应用场景

  1. API调用: “`php <?php \(ch = curl_init(); curl_setopt(\)ch, CURLOPT_URL, “https://api.example.com/data”); curl_setopt(\(ch, CURLOPT_RETURNTRANSFER, true); curl_setopt(\)ch, CURLOPT_HTTPHEADER, [ ‘Authorization: Bearer your_api_key’, ‘Accept: application/json’ ]); \(response = curl_exec(\)ch); curl_close($ch);

\(data = json_decode(\)response, true); ?> “`

  1. 网页抓取: “`php <?php \(ch = curl_init(); curl_setopt(\)ch, CURLOPT_URL, “http://example.com”); curl_setopt(\(ch, CURLOPT_RETURNTRANSFER, true); curl_setopt(\)ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt(\(ch, CURLOPT_USERAGENT, 'Mozilla/5.0'); \)html = curl_exec(\(ch); curl_close(\)ch);

// 使用DOM解析HTML \(dom = new DOMDocument(); @\)dom->load

推荐阅读:
  1. php curl函数封装
  2. PHP的curl功能扩展如何使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php curl

上一篇:eclipse中如何使用Lombok

下一篇:linux php如何安装pdo-oci扩展

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》