How to add curl HTTP Headers for authentication in PHP? - php

I want to add the HTTP headers for authenticating Udemy API access.Can someone tell me as to how to add the headers.I already have the client id and secret key.I want to access the API from a PHP page.
https://developers.udemy.com/
Here is the code i tried using:
$ch = curl_init($request);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id:MY_ID','X-Udemy-Client-Secret:Secret'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$results= curl_exec($ch);
echo $results;
Output:
Blank Page
Can someone point out what the problem might be?

As #drmarvelous wrote, you perform two requests (1st - by CURL, and 2nd - by file_get_contents) which does the same. Wherein the result of CURL request is not actually used in your script. It use the result of file_get_contents request which is performed without authentication parameters. Because of this you getting Unauthorized error.
So you have to use the result of CURL request:
...
$json = json_decode($results, true);
print_r($json);
Update:
You have to ensure you use valid URL for API request, i.e. value of $request in your code should be valid URL. Also, ensure you pass valid authentication parameters (Client-Id and Client-Secret) by HTTP headers.
Furthermore, since API is secured, you have to disable SSL peer verification by setting CURLOPT_SSL_VERIFYPEER option to false.
So the code should look like this:
$ch = curl_init($request);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id: {YourID}','X-Udemy-Client-Secret: {YourSecret}'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$results= curl_exec($ch);
echo $results;

Related

I am getting NULL data in response to cURL request

I am doing a cURL request to fetch information using api but when I use json_decode, it's not giving any information rather it's returning NULL value. Please go through these lines-
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,"http://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.html");
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
Is this correct way to make cURL request and fetch information using API, or suggest me how to do as I am new to this topic.
Your following line of code
$result=curl_exec($ch);
returning 301 Moved Permanently
since your URL is use HTTP only
http://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.htm
but this site runs on HTTPS, and server is setup to force/redirect this HTTP only URL to HTTPS i.e.
https://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.html
You can either change your url to https or set follow redirection true using
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirect if any
but still it renders HTML not JSON.
But in your comment you says this same URL is working with node, in such case please cross check your URL or try to make same request using POSTMAN and see what is shows

Curl request not working to use hasoffers api

I am using curl request to hit the has-offers conversion url from my sevrver with the help of curl but it is not working.But when I call the same URL using a browser, it works.Is they can block CURL requests?.I am not getting why, is there any port blocking issue.
Below is php code to call url using curl request.
<?php
function curl_get_contents($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url="http://paravey.go2cloud.org/aff_l?offer_id=12&aff_id=1000";
$contents = curl_get_contents($url);
echo $contents;
?>
Please help me thanks in Advance
The url you are curling is a pixel tracking url:
http://paravey.go2cloud.org/aff_l?offer_id=12&aff_id=1000
The aff_l endpoint looks for a cookie with session information (hence why it works in the browser).
If you want to create conversions with server side code, you will need to store the session identifier (the transaction_id) in your system and use the aff_lsr endpoint to send that data to HasOffers to trigger a conversion.
The url for this would look like this:
http://paravey.go2cloud.org/aff_lsr?transaction_id= VALUE
Where Value is the session identifier you have stored.
I would ask the HasOffers support team if you have more issues with this.

curl Request to Unverified Website

I am trying to use PHP's curl() function and for some reason my code does not return any data.
I am making a request to a URL that is unverified:
Here is my code:
<?php
$ch = curl_init("**SENSITIVE URL**");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
?>
If I put in www.google.com it does return the google webpage to my site. I apoligize, but I can't give out the URL for my site but I assure you that directly going to the URL does return data.
You need to tell cURL to ignore the (bad) SSL cert. Try adding the following options:
// Do not verify the cert
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Ignore the "does not match target host name" error
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

Simple Curl request not working

I have a function make_curl_request to make curl request.
/**
* General Function to make curl request */
function make_curl_request($url, $data)
{
ob_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($ch);
curl_close($ch);
$strCurlResponse = ob_get_contents();
ob_end_clean();
return $strCurlResponse;
}
I am calling it like:
$strGatewayResponse = make_curl_request( REQUEST_URL, compact('strMobileNo', 'strKeywords', 'strApiKey') );
I tried the things but can't get my code working fine. Currently its just return string("") as the output. Where am i going wrong?
My target is to simple post few data to next page located on other domain and get its xml response and parse it and display it. Is there any other simple and good solution?
The problem is that you've got RETURNTRANSFER set to TRUE, which means curl returns its output instead of directly outputting it. However, you're not capturing that output in a variable, so it's dropping on the floor.
You've got two options
a) remove the ob_*() functions to remove the PHP buffering and then do
$data = curl_exec($ch)
if ($data === FALSE) {
die("Curl failed: " . curL_error($ch));
}
after which $data contains the contents of the URL you've fetched.
b) remove the RETURNTRANSFER option, and let curl do its normal "output to client directly" thing, which then gets captured by the PHP output buffering.
Try by adding a row:
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.
it's not ok to send a curl POST without a header.
please find the following link. it may help
OAuth, PHP, Rest API and curl gives 400 Bad Request

cURL PHP RESTful service always returning FALSE

I am having some difficulties POSTing a json object to an API that uses REST. I am new to using cURL, but I have searched all over to try to find an answer to my problem but have come up short. My cURL request is always returning false. I know it isn't even posting my json object because I would still get a response from the url. My code is below.
<?php
//API KEY = APIUsername
//API_CODE = APIPassword
$API_Key = "some API key";
$API_Code = "some API code";
$API_email = "email#email.com";
$API_password = "ohhello";
$url = "http://someURL.com/rest.svc/blah";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
header('Content-type: application/json');
$authData = "{\"APIUsername\":\"$API_Key\",\"APIPassword\":\"$API_Code\",\"EmailAddress\":\"$API_email\",\"Password\":\"$API_password\"}";
curl_setopt($ch, CURLOPT_POSTFIELDS, $authData);
//make the request
$result = curl_exec($ch);
$response = json_encode($result);
echo $response;
curl_close()
?>
The $response returns just "false"
Any thoughts?
$response is likely false because curl_exec() returns false (i.e., failure) into $result. Echo out curl_error($ch) (after the call to curl_exec) to see the cURL error, if that's the problem.
On a different note, I think your CURLOPT_POSTFIELDS is in an invalid format. You don't pass a JSON string to that.
This parameter can either be passed as
a urlencoded string like
'para1=val1&para2=val2&...' or as an
array with the field name as key and
field data as value.
-- PHP docs for curl_setopt()
Update
The quick way to avoid the SSL error is to add this option:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
You get an SSL verification error because cURL, unlike browsers, does not have a preloaded list of trusted certificate authorities (CAs), so no SSL certificates are trusted by default. The quick solution is to just accept certificates without verification by using the line above. The better solution is to manually add only the certificate(s) or CA(s) you want to accept. See this article on cURL and SSL for more information.

Categories