Php curl post json example

How to POST and Receive JSON Data using PHP cURL

JSON is the most popular data format for exchanging data between a browser and a server. The JSON data format is mostly used in web services to interchange data through API. When you working with web services and APIs, sending JSON data via POST request is the most required functionality. PHP cURL makes it easy to POST JSON data to URL. In this tutorial, we will show you how to POST JSON data using PHP cURL and get JSON data in PHP.

Send JSON data via POST with PHP cURL

The following example makes an HTTP POST request and send the JSON data to URL with cURL in PHP.

  • Specify the URL ( $url ) where the JSON data to be sent.
  • Initiate new cURL resource using curl_init().
  • Setup data in PHP array and encode into a JSON string using json_encode().
  • Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option.
  • Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.
  • Return the response as a string instead of outputting it using the CURLOPT_RETURNTRANSFER option.
  • Finally, the curl_exec() function is used to execute the POST request.
// API URL $url = 'https://www.example.com/api'; 
// Create a new cURL resource $ch = curl_init($url);
// Setup request to send json via POST $data = array( 'username' => 'codexworld', 'password' => '123456' ); $payload = json_encode(array("user" => $data));
// Attach encoded JSON string to the POST fields curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set the content type to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// Return response instead of outputting curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the POST request $result = curl_exec($ch);
// Close cURL resource curl_close($ch);

Receive JSON POST Data using PHP

The following example shows how you can get or fetch the JSON POST data using PHP.

  • Use json_decode() function to decoded JSON data in PHP.
  • The file_get_contents() function is used to receive data in a more readable format.
$data = json_decode(file_get_contents('php://input'), true); 

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community — Ask Question

Источник

Примеры использования 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);

Чтобы 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);

Источник

Читайте также:  Create web pages with html
Оцените статью