PHP code example of chenbool / curl

1. Go to this page and download the library: Download chenbool/curl library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chenbool / curl example snippets





use chenbool\Curl;

// GET 请求
$response = Curl::init()->url('https://api.example.com/data')->data();

// POST 请求
$response = Curl::init()
    ->post(['name' => 'test', 'value' => 123])
    ->url('https://api.example.com/submit')
    ->data();

echo $response;

$curl = Curl::init();

// 简单 GET
$curl->url('https://api.example.com/users');

// 带查询参数
$curl->url('https://api.example.com/users?page=1&limit=10');

// 获取响应
if (!$curl->error()) {
    echo $curl->data();
} else {
    echo 'Error: ' . $curl->message();
}

$curl = Curl::init();

// 方式一:数组传参
$curl->post([
    'username' => 'admin',
    'password' => '123456'
])->url('https://api.example.com/login');

// 方式二:逐个设置
$curl->post('username', 'admin')
     ->post('password', '123456')
     ->url('https://api.example.com/login');

$curl = Curl::init();

// 单文件上传
$curl->post(['description' => '头像'])
     ->file('avatar', '/path/to/photo.jpg', 'image/jpeg', 'photo.jpg')
     ->url('https://api.example.com/upload');

// 多文件上传
$curl->post(['description' => '相册'])
     ->file('images[]', '/path/to/1.jpg', 'image/jpeg', '1.jpg')
     ->file('images[]', '/path/to/2.jpg', 'image/jpeg', '2.jpg')
     ->url('https://api.example.com/upload');

$curl = Curl::init();

// 下载并保存
$curl->url('https://example.com/file.zip')
     ->save('/path/to/save/file.zip');

if ($curl->error()) {
    echo 'Download failed: ' . $curl->message();
}

$curl = Curl::init();

// 自定义超时
$curl->set('CURLOPT_TIMEOUT', 60)
     ->set('CURLOPT_CONNECTTIMEOUT', 10);

// 设置请求头
$curl->set('CURLOPT_HTTPHEADER', [
    'Authorization: Bearer token123',
    'Content-Type: application/json'
]);

// 启用自动重试
$curl->retry(3)
     ->url('https://api.example.com/data');

$curl = Curl::init();

// 链式调用示例
$result = $curl
    ->set('CURLOPT_TIMEOUT', 30)
    ->set('CURLOPT_SSL_VERIFYPEER', false)
    ->post([
        'name' => 'test',
        'data' => json_encode(['key' => 'value'])
    ])
    ->retry(3)
    ->url('https://api.example.com/submit');

// 结果处理
if ($result->error()) {
    echo "请求失败: " . $result->message();
    print_r($result->info());  // 查看详细信息
} else {
    echo "响应内容: " . $result->data();
}