Php curl authorization bearer get

Simple OAuth2 authorization code grant example using PHP and cURL

The authorization code grant methods, should be very familiar if you’ve ever signed into an application using your Facebook or Google account.

The flow is quite simple. The application redirects the user to the authorization server >> the user will then be asked to log in to the authorization server and >> approve access to his data. And if the user approves the application >> he will be redirected back to the application.

So let’s start preparing the authorization code grant example.

We are using PHP v5.6.32 and cURL enabled extension on a Windows localhost machine. If you are using XAMPP you normally just have to uncomment this line to have cURL enabled.

you can find it in xampp \ apache \ bin \ php . ini or xampp \ php \ php . ini , depending on your XAMPP version and then restart Apache service.

So first you will need to collect your data and prepare some vars:

Now build your first URL to call. Normally you will want to call this URL in a popup window like old school times. You can also try a modern modal and use an iFrame but that didn’t work for me.

Читайте также:  Получить дочерний элемент css

So just use GET to retrieve the code param. Like this: $code = $_GET [ ‘code’ ] ;

This code is only valid for a short period of time and you will have to exchange the code for a token so you can make API calls. Here is the curl POST for receiving the token key:

If everything goes fine, you should get a JSON response similar to this one:

You can now use this token to make API calls and retrieve the info you’re after. You normally do a request to your endpoint using the token like this:

Just a small note here: token is normally valid for a short-to-medium period of time. When the token expires you can use the refresh token to request a new token. The refresh token should always be kept a secret on the server side, but this is subject of a new tutorial.

Still here?? Let me know your experience and maybe I can help you out there.

Leave a Reply Cancel reply

Recent Posts

How to embed video into a website – Ultimate tutorial Embedding a video into HTML website seems an easy task, but there really are lots of aspects to. PrettyPhoto Minimal Theme – a pure CSS prettyPhoto simple theme I have recently used prettyPhoto for a project and I have to admit that it is a great tool to have. Using preg_split() to explode() by multiple delimiters in PHP Just a quick note here. To [crayon-64b88fe7d33a7588487208-i/] a string using multiple delimiters. How to use PHP to insert content after or before HTML tag The problem is quite simple. you just want to count a specific tag on a page and insert some. Simple OAuth2 authorization code grant example using PHP and cURL The authorization code grant methods, should be very familiar if you’ve ever signed into an. Limit the number of keywords in WordPress tag cloud to control PageRank Did you know that the default wordpress tags, labels or keywords from the sidebar can have a huge. URL vs. URI vs. URN, What’s the difference / examples What is URI A URI identifies a resource either by location, or a name, or both. More often than. Build your own WordPress Twenty Sixteen Child Theme Child themes are very popular these days. We will create a simple child theme for the Twenty. Create a modal window using pure HTML5 and CSS3 In this tutorial we will create a modal window using only HTML5 and CSS3 properties. The techniques. Remove admin bar wordpress backend and frontend So, as mentioned above, supposedly the new Toolbar is meant to be impossible to remove. The reason. 7 years Google Adsense earnings statistics and 10.000$ barrier reached If you are on this page, there are lots of chances you have a Google Adsense account, you are. PHP logical operators true false The [crayon-64b88fe7d4253158817026-i/] and [crayon-64b88fe7d4258389204815-i/] logical operators. How to stop Google Analytics Language SPAM? Few days ago I have notice a big rise of my Google analytics stats from some very suspicious.

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.

Источник

Примеры использования cURL в PHP

cURL PHP – это библиотека функций PHP предназначенная для получения и передачи данных через такие протоколы, как HTTP, FTP, HTTPS . Библиотека используется для получения данных в виде XML , JSON и непосредственно в HTML , парсинга, загрузки и передачи файлов и т.д. Посылать HTTP запросы можно методами GET, POST, PUT, DELETE .

GET запрос

$ch = curl_init('https://example.com/v1/users'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); $errorCode = curl_errno($ch); $errorText = curl_error($ch); $info = curl_getinfo($ch); curl_close($ch); print_r(json_decode($response, true));

GET-запрос с параметрами

Получим пользователя по его ID:

$url = 'https://example.com'; $version = 'v1'; $resource = 'users'; $params = [ 'id' => 2200, ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf( "%s/%s/%s?%s", $url, $version, $resource, http_build_query($params) )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); curl_close($ch); print_r(json_decode($response, true));

POST запрос

$url = 'https://example.com'; $version = 'v1'; $resource = 'users'; $token = '876ef885733d24f5bc449f1611d2d1739a6ef56ca8a760f4bfa3610374101e58'; $params = [ 'email' => 'test@mail.com', 'name' => 'John Smith', 'gender' => 'male', 'status' => 'active', ]; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $token ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf( "%s/%s/%s", $url, $version, $resource )); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $response = curl_exec($ch); curl_close($ch); print_r(json_decode($response, true));

PUT запрос

Изменение пользователя по его ID:

$url = 'https://example.com'; $version = 'v1'; $resource = 'users/2200'; $token = '876ef885733d24f5bc449f1611d2d1739a6ef56ca8a760f4bfa3610374101e58'; $params = [ 'email' => 'test_update@mail.com' ]; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $token ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf( "%s/%s/%s?%s", $url, $version, $resource, http_build_query($params) )); curl_setopt($ch, CURLOPT_PUT, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); print_r(json_decode($response, true));

DELETE запрос

Удаление пользователя по его ID:

$url = 'https://example.com'; $version = 'v1'; $resource = 'users/2200'; $token = '876ef885733d24f5bc449f1611d2d1739a6ef56ca8a760f4bfa3610374101e58'; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $token ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf( "%s/%s/%s", $url, $version, $resource )); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); print_r(json_decode($response, true));

Basic авторизация

$url = 'https://example.com/auth.php'; $login = 'admin'; $password = 'password'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, "$login:$password"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_HEADER, false); $response = curl_exec($ch); curl_close($ch); print_r(json_decode($response, true));

Bearer авторизация

$url = 'https://example.com'; $version = 'v1'; $resource = 'users'; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer YOUR-TOKEN' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf( "%s/%s/%s", $url, $version, $resource )); curl_setopt($ch, CURLOPT_TIMEOUT, 0); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BEARER); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); print_r(json_decode($response, true));

OAuth авторизация

$headers = [ 'Content-Type: application/json', 'Authorization: OAuth YOUR-TOKEN' ];

Дополнительная информация о сеансе

$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); $errorCode = curl_errno($ch); // код последней ошибки $errorText = curl_error($ch); // описание последней ошибки $info = curl_getinfo($ch); // дополнительная информация о сеансе $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // код ответа сервера curl_close($ch); print_r($info); print_r($http_code);

Источник

PHP Curl Request With Bearer Token Authorization Header Example

This simple article demonstrates of php curl request with bearer token. i explained simply about curl post request with bearer token php. this example will help you rest api token based authentication example php. This tutorial will give you simple example of php curl with authorization header. Alright, let’s dive into the steps.

In this example, we will use CURLOPT_HTTPHEADER to pass authorization: bearer token for authorization. so let’s see bellow simple example code here:

/* API URL */

$url = ‘http://www.mysite.com/api’;

/* Init cURL resource */

$ch = curl_init($url);

/* Array Parameter Data */

$data = [‘name’=>’Hardik’, ’email’=>’itsolutionstuff@gmail.com’];

/* pass encoded JSON string to the POST fields */

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

/* set the content type json */

$headers = [];

$headers[] = ‘Content-Type:application/json’;

$token = «your_token»;

$headers[] = «Authorization: Bearer «.$token;

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

/* set return type json */

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

/* execute request */

$result = curl_exec($ch);

/* close cURL resource */

curl_close($ch);

?>

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

We are Recommending you

  • PHP Curl Delete Request Example Code
  • PHP Curl POST Request with Headers Example
  • PHP Curl Get Request with Parameters Example
  • PHP Curl Request with Certificate (cert pem file option) Example
  • How to Generate 4,6,8,10 Digit Random number in PHP?
  • PHP Get All Array Keys Starting with Certain String Example
  • PHP Convert XML to JSON Example
  • Codeigniter Curl Post Request with Parameters Example
  • PHP CURL Post Request with Parameters Example
  • Laravel CURL Request Example using Ixudra/curl
  • PHP Download File from URL using CURL Request Example

Источник

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