Базовая работа с PHP cURL: GET, POST, JSON, Headers
cURL — это программное обеспечение, которое позволяет выполнять запросы разных типов или протоколов. И как раз cURL помогает нам писать боты и парcеры на PHP, автоматизируя шаблонные HTTP-запросы, и собирая большое количество данных автоматизировано. PHP имеет встроенные инструменты по удобной работе с cURL.
PHP cURL основы
curl_init(); // инициализирует сессию работы с cURL curl_setopt(. ); // изменяет поведение cURL-сессии, в соответствии с переданными опциями curl_exec(); // выполняет cURL запрос по сконфигурированной сессии, и возвращает результат curl_close(); // закрывает сессию cURL и удаляет переменную, которой присвоен curl_init();
- curl_init ([ string $url = NULL ] ) — с него начинается инициализация сессии cURL
- curl_setopt ( resource $ch , int $option , mixed $value ) — конфигурирование настроек текущей сессии cURL
- curl_exec ( resource $ch ) — выполняем запрос, получаем результат
- curl_close ( resource $ch ) — закрытие сессии. В реальности, можно игнорировать выполнение curl_close(), так как PHP сделает это за нас, после выполнения скрипта
Отправка GET запроса из PHP cURL
Здесь всё просто, PHP cURL GET запрос — это самое простое, что можно придумать.
// URL страницы, которую открываем $url = 'https://orkhanalyshov.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
В результате выполнения этого кода, переменной $response будет присвоен ответ от сервера, к которому мы стучались (в основном — это HTML или JSON).
Иногда стоит необходимость отправки GET-запроса, формируя URL-адрес из Query-параметров. Для таких случаев, можете воспользоваться встроенной PHP-функцией, формирующей URL-строку с параметрами из массива:
$queryParams = [ 'category' => 14, 'page' => 2, ]; $url = 'https://alishoff.com/?' . http_build_query($queryParams); echo $url; // https://alishoff.com/?category=14&page=2
Отправка POST запроса из PHP cURL
PHP cURL POST запрос обычно не выполняется с пустым телом. Запрос этого типа считается запросом на добавление данных (создание новой сущности в БД, к примеру) и обычно нам необходимо передавать серверу набор каких-то данных. Код отправки POST-запроса с передачей данных будет выглядеть так:
// данные POST-запроса $data = [ 'name' => 'John', 'email' => 'john@doe.com', 'body' => 'Hello, World!', 'verifyCode' => 'cugifu', ]; // url, на который отправляет данные $url = 'https://alishoff.com/contact'; $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); var_dump($response);
Отправка cURL запроса из PHP с собственными заголовками (PHP cURL Headers)
Для того, чтобы передать дополнительные, собственные заголовки, нужно с помощью функции curl_setopt() задать опцию CURLOPT_HTTPHEADER, передав массив заголовков в формате Name: Header value:
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Custom-Header-1: The-Header-Value-1', 'Custom-Header-2: The-Header-Value-2' ]);
Отправка POST JSON запроса в PHP cURL
Очень часто, при написании ботов, имитирующих взаимодействие с API, приходится отправлять данные на целевой сервер в формате JSON. И так сложилось, что отправка Form-Data POST параметров отличается от алгоритма отправки JSON данных, потому, и передавать эти данные для cURL нужно по-другому.
Для того, чтобы корректно передать данные в формате JSON через PHP cURL, необходимо исходный массив с параметрами, перекодировать в JSON вручную, и заполнить этими данными тело (body) запроса. А так же, чтобы сервер понял, что это данные в формате JSON, нужно передать соответствующие HTTP-заголовки (о которых мы говорили выше).
$data = [ 'site' => 'https://orkhanalyshov.com', 'action' => 'notify', 'email' => 'john@doe.com', ]; $dataString = json_encode($data); $url = 'http://localhost/handler.php'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($dataString) ]); $result = curl_exec($ch); curl_close($ch);
Основной принцип передачи данных в JSON с помощью cURL заключается в том, что нужно выполнить POST запрос, тело которого заполнить закодированными в JSON данными, после чего, указать соответствующий заголовок позволяющий серверу понять, что ему на обработку пришли JSON данные.
How to Post JSON Data with PHP cURL & Receive It?
Hi! Here let’s see how to post json data with php curl and receive the raw json sent. You can simply use PHP file_get_contents() to send HTTP GET request. But it’s not the same case with HTTP POST. Fortunately PHP cURL makes the process very simple. With curl you can easily send HTTP requests. In case you don’t know, ‘cURL’ is a library that let you communicate with web servers using different protocols such as http, https, ftp, telnet, file etc.
To use curl, you must install libcurl package on your server according to the version of PHP you use.
In case you are not sure if curl is enabled on your machine or not, use this code to check it.
How to Post JSON with PHP cURL?
In order to send HTTP POST request with JSON data, you have to follow some steps and they are,
- Format JSON data correctly
- Attach JSON to the body of the POST request
- Set the right content type with HTTP headers
- Send the request.
The following is the PHP code to send json through POST request.
'mydomain.com', 'account' => 'admin', 'status' => 'true' ); $json = json_encode($data); // send post request $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); echo $result; ?>
Here is the explanation for the functions & curl options we have used in the above script:
- curl_init() — Initialize a curl session, takes up a parameter URL to send post request.
- curl_setopt() — Set the curl options.
- CURLOPT_POSTFIELDS — This option will set the data to the body of the http request.
- CURLOPT_HTTPHEADER — Option to set http headers. It is important to define the right content type here, so that the remote server understands what we sent. To send json, the content type should be set to ‘application/json’.
- CURLOPT_RETURNTRANSFER — Setting this to TRUE will place the response from the remote server on $result variable instead of outputting it.
- curl_exec() — Send the HTTP request.
- curl_close() — Close the curl session.
Retrieve the Posted JSON:
Okay! We have sent json data via http post request. But what will happen at the receiving end? How should we retrieve the incoming json?
Well! In our example we have sent raw json data. This can be accessed through php’s input stream. Below is the code to receive the json posted,
You can decode the json and process it as you want. Pretty simple!
That explains about posting json data and receiving it using PHP cURL. This is not very different from sending a regular POST request. However, we are doing it over HTTP here. Hopefully, this tutorial is useful for you. Please don’t forget to share it with your friends.