Php get json header

Retrieving JSON data in PHP using header

To decode a JSON response, it’s essential to remove the header. Fortunately, this can be done easily by utilizing the double-newline delimiter between the response’s header and body.

PHP Get JSON data from API with access token

Get data from JSON file with PHP, I’m trying to get data from the following JSON file using PHP. I specifically want «temperatureMin» and «temperatureMax». It’s probably really simple, but I have no idea how to do this. I’m stuck on what to do after file_get_contents(«file.json»). Some help would be greatly appreciated! Usage example$str = file_get_contents(‘http://example.com/example.json/’);Feedback

Parse JSON from GET response when headers are present

Passing json_decode is necessary for decoding JSON data. If you’re utilizing curl, it’s easy to configure the request to exclude headers and receive the desired results.

curl_setopt($ch, CURLOPT_HEADER, false); 

In case you require the headers for previous processing, the above approach may not suffice. Nonetheless, you can quickly eliminate them by capitalizing on the fact that a double-newline «delimiter» separates the response’s header and body. By utilizing explode in this manner, you can extract the body.

list(,$body) = explode("\n\n", $response, 2); 
json_decode(@file_get_contents('php://input'), true) 

To decode the JSON response, disabling the header is necessary. This can be achieved by using the provided code.

curl_setopt($handle, CURLOPT_HEADER, false); 

To utilize the information in the header, simply employ the curl_getinfo function. As an illustration, to retrieve the HTTP status code, utilize this function.

curl_getinfo($handle, CURLINFO_HTTP_CODE) 

Additional choices are available by consulting the get info manual found at http://php.net/manual/en/function.curl-getinfo.php.

Get json using php, Make sure that PHP Curl is enables in your php.ini. If you want to use fopen the setting allow_url_fopen must be ‘ON’ in your php.ini. Checkout phpinfo() for all the settings. Since PHP 5.2.0 the function json_decode is part of the core.

PHP — Get JSON body from HTTPS request

Based on the information given, it seems likely that the SSL certificate on your intended server is invalid.

In Case 2, verify if the php script output indicates the absence of https wrapper on the server.

Be cautious of cross-site https problems as your browser is more strict when using https than plain http. This means that if your main site uses https, your support scripts must also use https.

Читайте также:  V8res mngsrv form html

I recommend examining the ‘network’ tab of your browser and searching for any additional indications.

I trust that this will guide you towards the correct path.

Would you be willing to attempt these (searching for hints).

print "
json: '$json'"; print "
type: ".gettype($json); print "
last error: ".json_last_error();

The problem was identified as I had been sending a GET request instead of a POST request.

Initially, I overlooked the possibility of HTTPS being the problem since it was working fine without it. However, the issue has been resolved now.

PHP Get JSON POST Data, It seems like it’s a serialized data but not a json data, try php’s serialize() and unserialize() instead of json_****() functions – himeshc_IB Oct …

Источник

Php get json request php set header

I think option 2 is actually more compliant with OAuth 1, because won’t quote the parameters. will be compliant with RFC3986 which should help keep your values properly encoded. I think an easier way to avoid making these mistakes could be to either use something like and pass as the enc_type paremeter to be compliant with RFC3986, which is what OAuth 1.0a states it follows, or you could just set the parameters in a separate array and to encode them yourself.

Build HTTP GET request with headers and body PHP

You can use curl_setopt() with CURLOPT_HTTPHEADER to set custom headers.

 $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://www.google.co.in"); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'sessionToken:UniqueSessionTokenHere' )); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); 

PHP Get Cookies From Header String, I have a string variable containing the header response. like this This string is grabbed by sending PHP Get Cookies From Header String. Ask Question Asked 10 years, 11 I have a string variable containing the header response. like this. This string is grabbed by sending a request through fsockopen() and …

How to post JSON data and a request token(in the header) in cURL php

In your code above, you set a URL to curl_init() and you also passed another one in CURLOPT_URL option. You can’t do that in one cURL request.

If you are using OAuth 2.0 you can set the access token to CURLOPT_XOAUTH2_BEARER option.

More information, please refer to PHP manual on cURL Functions.

Build HTTP GET request with headers and body PHP, Build HTTP GET request with headers and body PHP. Ask Question Asked 5 years, 6 months ago. Modified 5 years, 6 months ago. Viewed 2k times 0 I need to retrieve order information from an API. This API needs to be You can use curl_setopt() with CURLOPT_HTTPHEADER to set custom headers.

How to add an Authorization header to a HTTP request with file_get_contents()?

According to the OAuth 1.0a spec

  1. Parameter names and values are encoded per Parameter Encoding.
  2. For each parameter, the name is immediately followed by an ‘=’ character (ASCII code 61), a ‘»‘ character (ASCII code 34), the parameter value (MAY be empty), and another ‘»‘ character (ASCII code 34).
  3. Parameters are separated by a comma character (ASCII code 44) and OPTIONAL linear whitespace per [RFC2617] .
  4. The OPTIONAL realm parameter is added and interpreted per [RFC2617] , section 1.2.
Читайте также:  Install python from bash

One issue is that you’re inserting \n ( LF ) characters into your header string, which isn’t allowed according to RFC2617. You also seem to be missing a comma after you oauth_token . It’s also unclear if you’re properly encoding your parameters.

I think an easier way to avoid making these mistakes could be to either use something like http_build_query and pass PHP_QUERY_RFC3986 as the enc_type paremeter to be compliant with RFC3986, which is what OAuth 1.0a states it follows, or you could just set the parameters in a separate array and array_map to encode them yourself.

$params = [ "realm" => $realm, /* optional */ "oauth_consumer_key" => $key, "oauth_token" => $token, "oauth_signature_method" => $sigmeth, "oauth_timestamp" => $timestamp, "oauth_nonce" => $nonce, "oauth_signature" => $sig, ]; 

option 1

/* This will give you the proper encoded string to include in your Authorization header */ $params = http_build_query($params, null, ',', PHP_QUERY_RFC3986); $opts = ["http" => ["header" => "Authorization: OAuth " . $params]]; $context = stream_context_create($opts); $data = file_get_contents($url, false, $context); 

option 2

$params = implode(',',array_map(function($v,$k) < return $k . '="' . rawurlencode($v) . '"'; >, $params, array_keys($params))); $opts = ["http" => ["header" => "Authorization: OAuth " . $params]]; $context = stream_context_create($opts); $data = file_get_contents($url, false, $context); 

I think option 2 is actually more compliant with OAuth 1, because http_build_query won’t quote the parameters. rawurlencode will be compliant with RFC3986 which should help keep your values properly encoded.

JSON PHP — W3Schools, PHP File explained: Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as …

Источник

Базовая работа с 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 сделает это за нас, после выполнения скрипта
Читайте также:  Change php version debian

Отправка 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 данные.

Источник

Оцените статью