Активный
- Тема Автор
- #1
Руководство по использованию cURL для HTTP запросов, работы с API и загрузки данных.
Базовый GET запрос
POST запрос с данными
POST запрос с JSON
Запрос с заголовками
Обработка ошибок
Загрузка файла
Сохранение ответа в файл
Множественные запросы
Класс для работы с API
Настройка таймаутов
Следование редиректам
Работа с cookies
cURL - мощный инструмент для работы с HTTP запросами в PHP. Эти примеры покрывают большинство сценариев использования.
Базовый GET запрос
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
echo $response;
} else {
echo "Ошибка: HTTP код " . $httpCode;
}
curl_close($ch);
?>
POST запрос с данными
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/post');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'name' => 'Иван',
'email' => 'ivan@example.com'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
POST запрос с JSON
Код:
<?php
$data = json_encode(['name' => 'Иван', 'age' => 25]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/json');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Запрос с заголовками
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer token123',
'X-API-Key: your-api-key',
'Accept: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>
Обработка ошибок
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo "Ошибка cURL: " . curl_error($ch);
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
echo $response;
} else {
echo "HTTP ошибка: " . $httpCode;
}
}
curl_close($ch);
?>
Загрузка файла
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/upload');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => new CURLFile('local_file.txt', 'text/plain', 'file.txt')
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>
Сохранение ответа в файл
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/image.jpg');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
file_put_contents('downloaded_image.jpg', $data);
curl_close($ch);
?>
Множественные запросы
Код:
<?php
$urls = [
'https://api.example.com/data1',
'https://api.example.com/data2',
'https://api.example.com/data3'
];
$mh = curl_multi_init();
$ch = [];
foreach ($urls as $i => $url) {
$ch[$i] = curl_init();
curl_setopt($ch[$i], CURLOPT_URL, $url);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch[$i]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
foreach ($ch as $i => $handle) {
$response = curl_multi_getcontent($handle);
echo "Ответ $i: " . $response . "\n";
curl_multi_remove_handle($mh, $handle);
curl_close($handle);
}
curl_multi_close($mh);
?>
Класс для работы с API
Код:
<?php
class ApiClient {
private $baseUrl;
private $apiKey;
public function __construct($baseUrl, $apiKey) {
$this->baseUrl = $baseUrl;
$this->apiKey = $apiKey;
}
public function get($endpoint, $params = []) {
$url = $this->baseUrl . $endpoint;
if (!empty($params)) {
$url .= '?' . http_build_query($params);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->apiKey
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
return json_decode($response, true);
}
return false;
}
public function post($endpoint, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->baseUrl . $endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->apiKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
// Использование
$api = new ApiClient('https://api.example.com', 'your-api-key');
$data = $api->get('/users', ['page' => 1]);
$result = $api->post('/users', ['name' => 'Иван']);
?>
Настройка таймаутов
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Общий таймаут
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // Таймаут подключения
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>
Следование редиректам
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>
Работа с cookies
Код:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/login');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'username' => 'user',
'password' => 'pass'
]));
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
// Использование cookies для следующего запроса
curl_setopt($ch, CURLOPT_URL, 'https://example.com/profile');
$response = curl_exec($ch);
curl_close($ch);
?>
cURL - мощный инструмент для работы с HTTP запросами в PHP. Эти примеры покрывают большинство сценариев использования.