I am trying to get a token to use the Microsoft Graph API (https://learn.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0) via Curl. I have set up a simple Php file with this function:
function getToken() {
echo "start gettoken";
var_dump(extension_loaded('curl'));
$jsonStr = http_build_query(Array(
"client_id" => "***",
"scope" => "https://graph.microsoft.com/.default",
"client_secret" => "***",
"grant_type" => "client_credentials"
));
$headers = Array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($jsonStr));
$ch = curl_init("https://login.microsoftonline.com/***.onmicrosoft.com/oauth2/v2.0/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$token = curl_exec($ch);
echo "test after curl";
return $token;
curl_error($ch);
}
However, what I want to know is why the curl request is not working. Also the echo after the curl codeblock is not being executed, while 'start gettoken' is. PHP_curl is enabled in my WAMP. Why is this?
Are you sure CURL is enabled because that code you have posted is ok and giving echo response before and after curl execution.
you're sending the token request in a JSON-format, and then you're lying to the server saying it's application/x-www-form-urlencoded-encoded when it's actually application/json-encoded! since these 2 formats are completely incompatible, the server fails to parse it, and... ideally it should have responded HTTP 400 bad request (because your request can't be parsed as x-www-form-urlencoded)
anyhow, to actually send it in the application/x-www-form-urlencoded-format, replace json_encode() with http_build_query()
also get rid of the "Content-Length:"-header, it's easy to mess up (aka error-prone) if you're doing it manually (and indeed, you messed it up! there's supposed to be a space between the : and the number, you didn't add the space, but the usual error is supplying the wrong length), but if you don't do it manually, then curl will create the header for you automatically, which is not error-prone.
Related
I am using Php as a frontend and Java as a backend. I have created an Post API for uploading file and using curl for api request.
I have hit my Api using Postman at that time it works fine but i am facing prodblem when i request api using Curl i don't eble to get what i am doing wrong.
Here is the curl requested data :-
$data2 = array(
'file' =>
'#' . $data1->file->tmp_name
. ';filename=' . $data1->file->name
. ';type=' . $data1->file->type
);
This is how i am sending curl request:-
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch,CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_HEADER, 1); //parveen
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //parveen
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data2);
$headers = array(
'Content-Type:'.$this->service->contentType,
'Launcher:'.$this->serverName,
'domain:'.$this->service->domain,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$this->responseBody=curl_exec($ch);
Links where i find this solution:-
enter link description here
I search a lot to find the solution but nothing is worked for me so please help me .
Thanks
the way you're trying to upload the file hasn't been supported since the PHP5 days, and even in 5.5+ you'd need CURLOPT_SAFE_UPLOAD to upload with #. use CURLFile when uploading files, like
$data2 = array(
'file' => new CURLFile($data1->file->name,$data1->file->type,$data1->file->tmp_name)
);
also, don't use CURLOPT_CUSTOMREQUEST for POST requests, just use CURLOPT_POST. (this is also true for GET requests and CURLOPT_HTTPGET )
also, check the return value of curl_setopt, if there was a problem setting your option, it returns bool(false), in which case you should use curl_error() to extract the error message. use something like
function ecurl_setopt($ch,int $option,$value){
if(!curl_setopt($ch,$option,$value)){
throw new \RuntimeException('curl_setopt failed! '.curl_error($ch));
}
}
and protip, whenever you're debugging curl code, use CURLOPT_VERBOSE, it prints lots of useful debugging info
I'm building my first Spotify application and right now I'm tackling the authorization process.
So far I have been successful in retrieving my State and Code from https://accounts.spotify.com/authorize
and now I'm sending a POST request via PHP CURL request to acquire my access token.
Spotify's instructions for this step
I keep getting the following JSON error response indicating that my grant_type is not valid and it offers me three valid options:
{"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}bool(true)
If you look at my code below, I believe I have set the correct grant_type of "authorization_code" but I'm getting the error. I have highlighted with '******' the code snippet of what I believe to be the correct line of code.
Can anyone see what I'm doing incorrectly? Here's the code I'm using to send the request:
// Get access tokens
$ch = curl_init();
// Specify the HTTP headers to send.
//Authorization: Basic <base64 encoded client_id:client_secret>
$ClientIDSpotify = "[my spotify app id]";
$ClientSecretSpotify = "[my secret code]";
$authorization = base64_encode ( "{$ClientIDSpotify}:{$ClientSecretSpotify}" );
$http_headers = array(
"Authorization: Basic {$authorization}"
);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $http_headers );
curl_setopt( $ch, CURLOPT_POST, true);
$spotify_url = "https://accounts.spotify.com/api/token";
curl_setopt( $ch, CURLOPT_URL, $spotify_url );
// *************************************************
// HERE'S WHERE I CORRECTLY SPECIFY THE GRANT TYPE
// *************************************************
$data['grant_type'] = "authorization_code";
$data['code'] = $authorizationCode;
$callbackURL = "[my callback URL]";
$data['redirect_uri'] = $callbackURL;
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response_json = curl_exec( $ch );
curl_close( $ch );
}
Just as a note to the last comment about switching to http_build_query, I had to URLDECODE the data, in order for Spotify to recognize it. Try using this line instead.
curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode(http_build_query($data)));
Seems to me like the POST body isn't being formatted correctly, everything else looks good.
My limited understanding of PHP tells me that your POST body looks like
{
"fields" : {
"code" : $authorizationCode,
"grant_type" : "authorization_code",
"redirect_uri" : "http://www.example.com/spotify/callback/index.php"
}
}
Of course, what you'd like to send is just
{
"code" : $authorizationCode,
"grant_type" : "authorization_code",
"redirect_uri" : "http://www.example.com/spotify/callback/index.php"
}
Therefore, try to set the $data object with
$data['grant_type'] = "authorization_code";
$data['code'] = $authorizationCode;
$data['redirect_uri'] = $callbackURL;
or even shorter
$data = array("grant_type" => "authorization_code", "code" => $authorizationCode, "redirect_uri" => $callbackURL);
Hope this helped!
OK, so I dug a little digging and found some code in the PHP CURL manual comments section. The problem with Spotify's documentation is it doesn't specify the format of the POST data to be sent. I assumed since Spotify was sending me JSON data that I should be sending my data in JSON format as well. So I was formatting the POST data as such:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
After reading through some documentation I decided to try this instead:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
I got exactly the results I needed:
{"access_token":"[long access token]","token_type":"Bearer","expires_in":3600,"refresh_token":"[long refresh token]"}
Thank you, Michael, for attempting to assist!
I need to send an XML string via HTTP POST to another server using the settings below...
POST /xmlreceive.asmx/CaseApplicationZipped HTTP/1.1
Host: www.dummyurl.co.uk
Content-Type: application/x-www-form-urlencoded
Content-Length: length
XMLApplication=XMLstring&byArray=base64string
I'm guessing I need to set this up via cURL or maybe fsockopen.
I've tried the following but not having any luck at getting it to work.
$url = "http://www.dummyurl.co.uk/XMLReceive.asmx/CaseApplicationZipped";
$headers = array(
"Content-Type: application/x-www-form-urlencoded"//,
);
$post = http_build_query(array('XMLApplication' => $XML, 'byArray' => $base64));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "response: ".$response;
The remote server gives the following response...
"Object reference not set to an instance of an object."
Not enough rep yet to comment, so I'll post this as an answer.
PHP's cURL automatically send the Host (from $url) and the Content-Length headers, so you don't need to specify those manually.
A handy function exists for building the $post string: http_build_query. It'll handle properly encoding your POST body. It would look something like
$post = http_build_query(array('XMLApplication' => $XML, 'byArray' => $base64));
If you want to log out the headers you received, check the curl_getopt function.
As for the error you received, it seems like you're passing the remote site things it doesn't expect. I can't speak for what you're passing or what the site's expecting, but Input string was not in a correct format seems to imply that your $XML is not formatted correctly, or is being passed as an incorrect parameter.
I'm probably not supposed to use file_get_contents() What should I use? I'd like to keep it simple.
Warning: file_get_contents(http://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
The problem you are running into here is related to the MW API's User-Agent policy - you must supply a User-Agent header, and that header must supply some means of contacting you.
You can do this with file_get_contents() with a stream context:
$opts = array('http' =>
array(
'user_agent' => 'MyBot/1.0 (http://www.mysite.com/)'
)
);
$context = stream_context_create($opts);
$url = 'http://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0';
var_dump(file_get_contents($url, FALSE, $context));
Having said that, it might be considered more "standard" to use cURL, and this will certainly give you more control:
$url = 'http://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'MyBot/1.0 (http://www.mysite.com/)');
$result = curl_exec($ch);
if (!$result) {
exit('cURL Error: '.curl_error($ch));
}
var_dump($result);
The error message you are really receiving is
Scripts should use an informative User-Agent string with contact information, or they may be IP-blocked without notice.
This means that you should provide additional details about yourself when using the API. Your usage of file_get_contents does send the required User-Agent.
Here is a working example in curl that identifies itself as a Test for this question:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0&format=xml");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Testing for http://stackoverflow.com/questions/8956331/how-to-get-results-from-the-wikipedia-api-with-php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
file_get_contents Should work.
file_get_contents('http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=New_York_Yankees&rvprop=timestamp|user|comment|content')
This was previously discussed on stackoverflow here
Also, some nice looking code samples here
They themselves say in their API documentation:
Use any programming language to make an HTTP GET request for that URL
You need to get the URL right, thefollowing worksfor me :
http://en.wikipedia.org/w/api.php?format=json&action=query&titles=Main%20Page&prop=revisions&rvprop=content
you are not specifying the output format as far as I can notice right now!
I am trying to post to a REST service using PHP cURL but I'm after running into a bit of difficulty (this being that I've never used cURL before!!).
I've put together this code:
<?php
error_reporting(E_ALL);
if ($result == "00")
{
$url = 'http://127.0.0.1/xxxxxx/AccountCreator.ashx'; /*I've tried it a combination of ways just to see which might work */
$curl_post_data = array(
'companyName' =>urlencode($companyName),
'mainContact' =>urlencode($mainContact),
'telephone1' =>urlencode($telephone1),
'email' => urlencode($email),
'contact2' => urlencode($contact2),
'telephone2' => urlencode($telephone2)
'email2' => urlencode($email2);
'package' => urlencode($package)
);
foreach($curl_post_data as $key=>$value) {$fields_string .=$key. '=' .$value.'&';
}
rtrim($fields_string, '&');
die("Test: ".$fields_string);
$ch = curl_init();
curl_setopt ($ch, CURLOPT, $url);
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
Following this, my code sends an email and performs an IF statement. I know this works okay, I only started running into trouble when I tried to insert this cURL request.
I've tried this however it doesn't run. As I am integrating with payment partners, it just says:
Your transaction has been successful but there was a problem connecting back to the merchant's web site. Please contact the merchant and advise them that you received this error message. Thank you.
The exact error that was received was a HTTP 500 error.
Thanks.
foreach($curl_post_data as $key=>value) {$fields_string .=$key. '=' .value.'&';
value here is missing a dollar i guess
foreach($curl_post_data as $key => $value) {$fields_string .=$key. '=' .$value.'&';
have you tried die($fields_string); to see what are you actually sending to the merchant?
First of all: are you testing locally? Because that IP you're using is not a valid server address.
The constant to set the URL is called CURLOPT_URL:
curl_setopt ($ch, CURLOPT_URL, $url);
Also CURLOPT_POST must be true or false ( http://php.net/curl_setopt ), not a number (except for 1 maybe):
curl_setopt ($ch, CURLOPT_POST, true);
Here's some POST sample code: PHP + curl, HTTP POST sample code?
It would be best if you can provide your PHP version.
As of PHP 5, some handy functions are bundled in the core instead of separate PECL libraries.
// If you are working with normal HTTP requests, simply do this.
$curl_post_data = http_build_query($curl_post_data);
curl_setopt($ch, CURLOPT, $url);
// This is a boolean option, although passing non-zero integer
// will be type-casted to TRUE, count() is not the proper way.
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_post_data);
// If you really want the next statement be meaningful, do this.
// Otherwise your HTTP response will be passed directly into
// the output buffer.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
Keep in mind that CURLOPT_POSTFIELDS in PHP supports file uploads, by adding a '#' character followed by a full file path as the value.
You don't want to call http_build_query() on such situations.
Sample code for file upload
$curl_post_data = array('file1' => '#/home/user/files_to_be_uploaded');
While you can optionally specify MIME type, see the documentation for more information.
As said, check your PHP version first. This feature only works in PHP 5, AFAIK there are companies still hosting PHP 4.x in their servers.
Have a look at http_build_query