- Примеры использования cURL в PHP
- GET запрос
- GET-запрос с параметрами
- POST запрос
- Отправка JSON через POST-запрос
- PUT запрос
- DELETE запрос
- Запрос через proxy
- Отправка файлов на другой сервер
- До PHP 5.5
- Скачивание файлов
- Отправить и получить cookie
- Имитация браузера
- HTTP авторизация
- Basic Authorization
- OAuth авторизация
- Получить HTTP код ответа сервера
- Если CURL возвращает false
- PHP: Using cURL with Basic HTTP Authentication.
- 401 Unauthorized.
- Using the CURLOPT_USERPWD option.
- Using CURLOPT_HTTPHEADER.
Примеры использования cURL в PHP
cURL PHP – это библиотека предназначенная для получения и передачи данных через такие протоколы, как HTTP, FTP, HTTPS. Библиотека используется для получения данных в виде XML, JSON и непосредственно в HTML, парсинга, загрузки и передачи файлов и т.д.
GET запрос
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
GET-запрос с параметрами
$get = array( 'name' => 'Alex', 'email' => 'mail@example.com' ); $ch = curl_init('https://example.com?' . http_build_query($get)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
POST запрос
$array = array( 'login' => 'admin', 'password' => '1234' ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array, '', '&')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
Отправка JSON через POST-запрос
$data = array( 'name' => 'Маффин', 'price' => 100.0 ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch); $res = json_encode($res, JSON_UNESCAPED_UNICODE); print_r($res);
PUT запрос
HTTP-метод PUT используется в REST API для обновления данных.
$data = array( 'name' => 'Маффин', 'price' => 100.0 ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array, '', '&')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
DELETE запрос
HTTP-метод DELETE используется в REST API для удаления объектов.
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch);
Запрос через proxy
$proxy = '165.22.115.179:8080'; $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_TIMEOUT, 400); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch);
Отправка файлов на другой сервер
Отправка файлов осуществляется методом POST :
До PHP 5.5
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array('photo' => '@' . __DIR__ . '/image.png'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch);
С PHP 5.5 следует применять CURLFile.
$curl_file = curl_file_create(__DIR__ . '/image.png', 'image/png' , 'image.png'); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array('photo' => $curl_file)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch);
Также через curl можно отправить сразу несколько файлов:
$curl_files = array( 'photo[0]' => curl_file_create(__DIR__ . '/image.png', 'image/png' , 'image.png'), 'photo[1]' => curl_file_create(__DIR__ . '/image-2.png', 'image/png' , 'image-2.png') ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_files); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch);
Ещё файлы можно отправить методом PUT , например так загружаются файлы в REST API Яндекс Диска.
$file = __DIR__ . '/image.jpg'; $fp = fopen($file, 'r'); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_PUT, true); curl_setopt($ch, CURLOPT_UPLOAD, true); curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file)); curl_setopt($ch, CURLOPT_INFILE, $fp); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch);
Скачивание файлов
Curl позволяет сохранить результат сразу в файл, указав указатель на открытый файл в параметре CURLOPT_FILE .
$file_name = __DIR__ . '/file.html'; $file = @fopen($file_name, 'w'); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_FILE, $file); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch); fclose($file);
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); file_put_contents(__DIR__ . '/file.html', $html);
Отправить и получить cookie
Чтобы CURL сохранял куки в файле достаточно прописать его путь в параметрах CURLOPT_COOKIEFILE и CURLOPT_COOKIEJAR .
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__ . '/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__ . '/cookie.txt'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch);
Передать значение кук можно принудительно через параметр CURLOPT_COOKIE .
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=61445603b6a0809b061080ed4bb93da3'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch);
Имитация браузера
На многих сайтах есть защита от парсинга. Она основана на том что браузер передает серверу user agent , referer , cookie . Сервер проверяет эти данные и возвращает нормальную страницу. При подключение через curl эти данные не передаются и сервер отдает ошибку 404 или 500. Чтобы имитировать браузер нужно добавить заголовки:
$headers = array( 'cache-control: max-age=0', 'upgrade-insecure-requests: 1', 'user-agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36', 'sec-fetch-user: ?1', 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'x-compress: null', 'sec-fetch-site: none', 'sec-fetch-mode: navigate', 'accept-encoding: deflate, br', 'accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__ . '/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__ . '/cookie.txt'); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, true); $html = curl_exec($ch); curl_close($ch); echo $html;
HTTP авторизация
Basic Authorization
Если на сервере настроена HTTP авторизация, например с помощью .htpasswd, подключится к нему можно с помощью параметра CURLOPT_USERPWD .
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_USERPWD, 'login:password'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
OAuth авторизация
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: OAuth TOKEN')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
Получить HTTP код ответа сервера
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); echo $http_code; // Выведет: 200
Если CURL возвращает false
Какая произошла ошибка можно узнать с помощью функции curl_errno() .
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); $res = curl_exec($ch); var_dump($res); // false if ($errno = curl_errno($ch)) < $message = curl_strerror($errno); echo "cURL error ():\n "; // Выведет: cURL error (35): SSL connect error > curl_close($ch);
PHP: Using cURL with Basic HTTP Authentication.
This is a short PHP tutorial on how to use cURL to make a Basic Access Authentication request. In this post, I will show you how to configure PHP’s cURL functions to access a web resource that is protected by basic HTTP authentication.
401 Unauthorized.
If you send a cURL request to a URL that is protected by HTTP authentication, the response will probably look something like this:
401 Unauthorized: You need a valid user and password to access this content.
The issue here is that the resource is protected and you did not provide a valid username and password. As a result, the server responded with a 401 Unauthorized response.
Using the CURLOPT_USERPWD option.
To solve this, we can use the CURLOPT_USERPWD option. This option allows us to tell cURL what username and password to use while making the request.
An example of it being used:
//The URL of the resource that is protected by Basic HTTP Authentication. $url = 'http://site.com/protected.html'; //Your username. $username = 'myusername'; //Your password. $password = 'mypassword'; //Initiate cURL. $ch = curl_init($url); //Specify the username and password using the CURLOPT_USERPWD option. curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); //Tell cURL to return the output as a string instead //of dumping it to the browser. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Execute the cURL request. $response = curl_exec($ch); //Check for errors. if(curl_errno($ch)) < //If an error occured, throw an Exception. throw new Exception(curl_error($ch)); >//Print out the response. echo $response;
In the example above, we set the username and password using the CURLOPT_USERPWD option. As a result, our cURL client will end up sending the following header:
Authorization: Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk
- In some cases, the resource in question might be expecting a POST request. Therefore, you might need to change the request above from a GET request to a POST request.
- The CURLOPT_USERPWD option sends the username and password combination in a base64 format. This means that a combination of “MyUsername:MyPassword” will become “TXlVc2VybmFtZTpNeVBhc3N3b3Jk”. However, it is important to note that base64 does not make this request any more secure. Therefore, it is advisable that you configure both the cURL client and the server to use SSL. This is to prevent man-in-the-middle attacks.
- Other options may need to be configured depending on your situation. In other words, the code above might not work “straight out of the box”.
Using CURLOPT_HTTPHEADER.
Alternatively, you can use the CURLOPT_HTTPHEADER, which allows you manually create headers. In the example below, we manually set the Content-Type and Authorization headers:
//HTTP username. $username = 'myusername'; //HTTP password. $password = 'mypassword'; //Create the headers array. $headers = array( 'Content-Type: application/json', 'Authorization: Basic '. base64_encode("$username:$password") ); //Set the headers that we want our cURL client to use. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
The code above should be used in lieu of the CURLOPT_USERPWD option.
Hopefully, you found this guide to be useful!