- Using CURL with PHP to send POST field data using http header Authentication
- Categories
- PHP cURL API calls with authentication (REST GET POST)
- Generating an auth key
- How to use our Auth-token?
- cURL GET request (with Authentication)
- cURL POST request (with Authentication)
- No Access-Control-Allow-Origin header is present – (CORS)
- Get the latest posts and other things in your inbox
- Thank You!
- Read more related topics?
- Leave a Reply Cancel reply
- 10 Comments
- Как авторизоваться по ApiKey?
- php - Send APi key and secret key in CURL
- Answer
- Solution:
- Share solution ↓
- Additional Information:
- Didn't find the answer?
- Similar questions
Using CURL with PHP to send POST field data using http header Authentication
Okay, so until now I had been using api keys passed through the post fields but on a more recent project I was asked to send the api key through the headers when making the request, so I have made myself a little function to use curl and pass the api key through CURLOPT_HTTPHEADER.
function my_curl_request($postfields) < //define the end point url and api key $api_end_point_url = "https://some_end_point_url.com/api/" $api_key = "ABC123"; //urlify the data for the POST $fields_string = http_build_query($postfields); //prepare curl request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_end_point_url); curl_setopt($ch, CURLOPT_HTTPHEADER, [$api_key]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_POST, count($postfields)); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); //needed for https curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //make the request $result = curl_exec($ch); curl_close($ch); return $result; >
This will be the call to your curl function and you can print out the results of the call.
//define the data to send to the api $postfields = array( 'first_name' => "Joe", 'last_name' => "Bloggs", ); //make the request to the api. $result = my_curl_request($postfields); //echo results echo $result;
Categories
- About Blogging (9)
- Client Copia (10)
- Coding (60)
- Crazy Stuff (17)
- Domain Names (8)
- Free Stuff (1)
- Internet Business (30)
- Internet Design (15)
- Internet Marketing (113)
- Internet Security (20)
- Keywords (9)
- Mystery Solved (19)
- Nifty Tools (4)
- Off Site Marketing (47)
- Office (3)
- On Site Marketing (35)
- Personal Blog (18)
- Samsung Test Lab (1)
- Security Updates and Warnings (27)
- Uncategorized (1)
- Windows Vista (1)
- WordPress (6)
PHP cURL API calls with authentication (REST GET POST)
If you’re here because you want to connect your php code to an external API, please check my cURL api-calls with php tutorial first. This is part 2 of how to connect to an API using cURL in php, as I received a lot of questions on how to connect if the API requires authentication (utoken) first.
Heads up: This time, I will be using Javascript for more flexibility. As I need to make an ‘authentication’ api call first before our initial GET call. Therefore I create my API calls in my own php files on the side, and will target these files using ES6 async/fetch from within my page. If you see me linking to my-site.com, this means I created the file myself, on my own server. If I’m linking to api-site.com, this means I’m making a call the the external API.
Generating an auth key
Some API’s only allow POST or GET requests if you use an auth-token. We need to generate this auth-token first, before we are allowed to make API calls. Normally the API docs should explain how you can generate their auth-token. In my example, I can generate an auth-token by posting my API client ID, client_secret and a login type to their API Auth file.
Here is how I can generate and use my auth-token, based on the cURL script of my part-1 tutorial. In this tutorial, I’ll be calling this file api/auth.php
$curl = curl_init(); $auth_data = array( 'client_id' => 'XBnKaywRCrj05mM-XXX-6DXuZ3FFkUgiw45', 'client_secret' => 'btHTWVNMUATHEnF-XXX-2nQabKcKVo3VXtU', 'grant_type' => 'client_credentials' ); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $auth_data); curl_setopt($curl, CURLOPT_URL, 'https://api-site.com/oauth/token'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $result = curl_exec($curl); if(!$result) curl_close($curl); echo $result;
This will return an auth-token for me. With this auth token, I can start making normal API calls like POST and GET. However.. My example API only keeps my auth-token alive for 2 weeks AND will only allow 3 auth-tokens at a time. So for each call I make, I need to regenerate this. This is why I’m using JS as example, so we can easily quickly generate the AUTH token before our own call. For this, I have a separate JS function to post to our own api/auth.php: JS
const apiAuth = async () => < try< const response = await fetch('https://my-site.com/api/auth.php'); if(response.ok)< return response.json(); >throw new Error(`apiAuth_response: $`); >catch(error)< console.error(`apiAuth: $`); > >
This is the JS-script and the PHP-script I’m using to generate an auth-token for my API. I’m using await to make sure our script only continuous when we do have received the Auth token. If we don’t await this token, it’s possible the rest of our script will already try to make the API call without the utoken, and will return errors.
How to use our Auth-token?
Ok good, now we have an auth-token for our app… How do we use this?
cURL GET request (with Authentication)
In most cases (I think) you need to add your auth-token to the url you’re using to make a valid API call. Again, you should be able to find this in the documentation of the API your using. In my example, if I want to make an API call, my link should look like this: api/get_all_reviews.php
https://api-site.com/v1/apps/' . $app_key . '/reviews?utoken=' . $utoken;
We do know our $app_key and we just generated our $utoken. So our .php file to make the GET-call would look like this: ($_POST[‘auth_token’] will be our received utoken from our previous function.
if(isset($_POST['access_token'])) < $app_key = 'XBnKaywRCrj05m-XXX-v6DXuZ3FFkUgiw45'; $utoken = $_POST['access_token']; $url = 'https://api-site.com/v1/apps/' . $app_key . '/reviews?utoken=' . $utoken; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $result = curl_exec($curl); if(!$result)curl_close($curl); echo $result; >
This will return all our product-reviews in the example I picked for this tutorial. Now we still need to target this GET php file with our JS and don’t forget to generate our utoken first! JS
const getAllReviews = async () => < const auth = await apiAuth(); const data = < access_token: auth.access_token, token_type: auth.token_type, >try< $.post(< type: 'POST', url: 'http://my-site.com/api/get_all_reviews.php', data: data >) .success(res => < const data = JSON.parse(res); const reviews = data.reviews; displayAllReviews(reviews, $('.review-list')); >); >catch(error)< console.error(`getAllReviews: $`); > >
As you can see we await the Auth function again, before we continue with our original API call. We post the received auth.access_token together with our form data to our GET php script. The displayAllReviews() is a random function, that I am passing our received data to. So here you can call your own functions, depending on what you want to do with this data.
cURL POST request (with Authentication)
Same for POST as with GET, we need to add our utoken (Auth-token) to the url. Here is an example of my POST link to the API, with my utoken: api/post_review.php
if(isset($_POST['success'])) < $p_url = 'https://product-link.com'; $email = $_POST['email']; $post_array = array( 'appkey' =>'XBnKaywRCrj05m-XXX-v6DXuZ3FFkUgiw45', 'domain' => 'https://api-site.com', 'product_url' => $p_url, 'email' => $email, 'review_content' => $_POST['message'], 'review_title' => $_POST['title'], 'review_score' => $_POST['star_rating_value'] ); postReview($post_array); >else < $response = array( 'response' =>'error', 'message' => 'POST is required to use this function' ); > function postReview($post_array) < $curl = curl_init(); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_array); curl_setopt($curl, CURLOPT_URL, 'https://api-site.com/v1/reviews'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $result = curl_exec($curl); if(!$result)curl_close($curl); echo $result; >
To make a POST, I first gather all the information I need to make the post. (like user-email and the product URL I want to post a review for). When I have all the data, I call the postReview function, that will make the POST API call. We need to gather all this data up-front, otherwise we are not allowed to make our API call. As our POST request doesn’t require a utoken variable.
Now the JS script I used for this: JS
function postSiteReview(data, form)< $.ajax(< url: 'https://my-site.com/api/post_review.php', type: 'post', data: data, success: function(result)< let res = JSON.parse(result); let message = ''; if(res.code === 200)< form.find('.success-message').fadeIn(); >else < if(res.response === 'error')< message = res.message; >if(res.status && res.status.code === 500) < message = res.status.message; >$('p.error-msg').text(`Uh ooh.. $`); > >, error: function(err) < console.log('$.ajax error: ' + err); >>); >
No Access-Control-Allow-Origin header is present – (CORS)
If you’re making JS calls to your own php-files, but your files are on a different server, please at following line at the top of each .php file you’re using:
header("Access-Control-Allow-Origin: https://my-site.com");
This should fix the access-control error you’re seeing in the js-console.
I really hope this part is well-explained as well. If not, please feel free to ask in the comments. (I can not guarantee you will get a response).
Let me know if it works for you.
Happy coding!
Get the latest posts and other things in your inbox
Receive our best-off articles straight in your inbox! Just once each quarter, because no one likes spam.
Thank You!
Thank you for subscribing. Our thank you message is already heading your way!
Read more related topics?
Leave a Reply Cancel reply
10 Comments
Hi weichie, I’ve been struggling to call external API using cURL and php. I have client secret and client id as well as callback URL but i cannot get the user email or user id. Can you help me with this?
i really appreciated your efforts to explain this concept succinctly.
all other parts of this tutorial work smoothly as expected.
However, i did not fully get the javascript implementation.
for this function “function postSiteReview(data, form)” kindly explain the meaning of the parameters how to invoke it.
You may always reach out to me through the contact page. Please note that I cannot offer one-on-one support for every request, but you can always try your chances.
Hi,
first of all thanks a lot for this post.
Here $app_key and client_id both are the same ?
$auth_data = array(
‘client_id’ => ‘XBnKaywRCrj05mM-XXX-6DXuZ3FFkUgiw45’,
‘client_secret’ => ‘btHTWVNMUATHEnF-XXX-2nQabKcKVo3VXtU’,
‘grant_type’ => ‘client_credentials’
);
here client_credentials means username and password that will be provided by the api provider ?
Oh, I see $_POST in the PHP documentation. I guess I’m not using it right, though. It doesn’t seem to be working for me. I’m guessing [‘access_token’] is an endpoint specific to your API.
How do you authenticate when calling https://my-site.com/api/auth.php? or can anyone call this service and get a valid auth token?
Anyone can call the url, but only if you post the correct user data you will receive a valid auth token. Otherwise it should return an error like ‘invalid user credentials’ or something
Как авторизоваться по ApiKey?
Подскажите плс, я по описанию пытаюсь получить токен по api key,
Ответ должен прийти вот таким:
Access_token
Токен для работы с api
eyJhbGciOiJQUzI1NiIsInR5cCI6ImF0K2p3dCJ9
$url = "https://shate-m.kz/api/v1/auth/loginByKey"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $headers = array( "Content-Type: application/x-www-form-urlencoded", "Authorization: Bearer тут токен", ); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); //for debug only! curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $resp = curl_exec($curl); curl_close($curl); echo ''; print_r($resp); echo ''
В ответ я получаю error 404
Простой 2 комментария
передать ApiKey (получаете от Вашего менеджера) с телом запроса типа Content-type application/x-www-form-urlencoded.
Ты не туда стучишься. Документация API.
Я так понял надо сюда стучаться https://api.shate-m.kz/api/v1/auth/loginByKey
$url = 'https://api.shate-m.kz/api/v1/auth/loginbyapikey'; $headers = array( "accept: text/plain", "Content-Type: application/x-www-form-urlencoded", ); $apikey = array( "ApiKey" => "apikey" ); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_HTTPHEADER, $headers, CURLOPT_POSTFIELDS, json_encode($apikey, JSON_UNESCAPED_UNICODE), CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => FALSE, CURLOPT_POST => 1, CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, )); if(!$result = curl_exec($curl)) < $result = curl_error($curl); >curl_close($curl); $result = json_decode($result, true); echo ''; print_r($result); echo '';
Array ( [code] => RequestModelValidationError [description] => Ошибка валидации параметров запроса [traceId] => 00-02b31948e1eb8545c7d59980fee25463-975a0dc5ba76cf64-00 [messages] => Array ( [0] => ApiKey: The ApiKey field is required. ) )
Он не видит ключ апи, я его как то неправильно отправляю?
php - Send APi key and secret key in CURL
I'm trying to convert the line below to be used with PHP whilst also learning how to use CURL!
$ curl -X POST -d 'key=YOUR_KEY&secret=YOUR_SECRET' "https://api.example.co.uk/authenticate" -H "Content-Type: application/x-www-form-urlencoded"
Bellow is what I have so far, however I keep getting HTTP ERROR 403 UnauthorizedException accessing service error, so I think the key and secret and not being sent correctly.
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.example.co.uk/authenticate", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "", CURLOPT_HTTPHEADER => array( "content-type: application/x-www-form-urlencoded" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) < echo "cURL Error #:" . $err; >else
Answer
Solution:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.example.co.uk/authenticate'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "key=YOUR_KEY&secret=YOUR_SECRET"); $headers = array(); $headers[] = 'Content-Type: application/x-www-form-urlencoded'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) < echo 'Error:' . curl_error($ch); >curl_close($ch);
Share solution ↓
Additional Information:
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.