- Базовая работа с PHP cURL: GET, POST, JSON, Headers
- How to create a JSON object and send it as POST request using PHP
- JSON Syntax
- Example
- How to create a JSON object in PHP
- How to create a JSON object with an array and nested object
- Example
- Sending a JSON object as a post request in PHP
- Conclusion
- Related Articles
Базовая работа с 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 create a JSON object and send it as POST request using PHP
JavaScript Object Notation(JSON) is a lightweight human-readable text format for storing and transporting data consisting of name-value pairs and arrays.
It is commonly used in reading data from a web server, and displaying it on a web page.
JSON data can easily be sent between computers, applications, and can be used by any programming language. It is extensively used as the de-facto format for the data exchange in RESTful web services requests and responses. In fact, the success of RESTful web services can be attributed to the JSON format due to its ease of use on various platforms and languages.
JSON Syntax
Data in JSON objects is stored in name-value pairs, as in the example below:
From the above example, “firstName” is the name, and “John” is the value.
The name in the pair is always a string while its value can be of different data types which include: string, number, object, array, true, false, and null.
The name and value in a pair are separated by a colon (:).
The name-value pairs are separated by a comma (,).
The JSON object is enclosed in curly braces (<>). It can contain name-value pairs and/or arrays.
Arrays in JSON are enclosed square brackets ([]), and their values are separated by a comma (,).
Example
The above is an example of a JSON object containing data in name-value pairs. It has values of datatypes: string, number, object and array.
The value for the name «phoneNumbers» is an array of two objects.
The value for the name «address» is an object containing 3 name-value pairs.
The name «age» contains a value of type number.
How to create a JSON object in PHP
First is to create an array, then encode it into a JSON object.
Since data in JSON is stored in name-value pairs, we use the associative arrays which also store data in key-value pairs, where the key is used as an index to search the corresponding value in the array.
To create an associative array in PHP, we put our key-value pairs inside the array() function and use the double arrow operator (=>) to assign values to keys.
"John", "lastName" => "Doe", "email" => "johndoe@gmail.com", "phone" => "111-111-1111" );
After creating an associative array, then convert it into a JSON object using the PHP inbuilt json_encode() function as shown below.
Add a Content-Type header by adding header(«Content-Type:application/json») at the top of the PHP file for your output to be recognized as a JSON object.
"John", "lastName" => "Doe", "email" => "johndoe@gmail.com", "phone" => "111-111-1111" $jsonobject = json_encode($myobj); echo $jsonobject;
The above code will print out a JSON object as below:
How to create a JSON object with an array and nested object
To have a name with an object as its value, will just need to create an array and assign it to the key as the value while forming the associative array.
To have a name with an array value, we just need to create an array as the value, then create other arrays with key-value pairs inside it.
Example
"John", "lastName" => "Doe", "email" => "johndoe@gmail.com", "address" => array( "postalAddress" => "12345", "postalCode" => "5432", "city" => "Nairobi" ), "siblings" => array( array( "name" => "Joseph Doe" ), array( "name" => "Mary Doe" ) ) ); $jsonobject = json_encode($myarray); echo $jsonobject;
The above code will output a JSON object below:
Sending a JSON object as a post request in PHP
Now that you already know how to form a JSON object, let’s dive into how you can send it as POST request.
We will achieve that using PHP Curl as shown below:
"John", "lastName" => "Doe", "email" => "johndoe@gmail.com", "phone" => "111-111-1111" ); $url = "https://www.example.com/register" $payload = json_encode($myarray); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); curl_exec($curl); curl_close($curl);
Conclusion
In this tutorial we have covered what JSON is, why it’s important, how to create associative arrays in PHP, how to convert an associative array into a JSON object and how to send the created object in a POST request using PHP curl.