PHP curl for the sc2ranks.com API - php

This is the first question ever here, so I'll do my best.
Background
I'm working on a small Starcraft II website that uses an API from a well known website. After looking at the documentation I got the example working rather quickly, returning the JSON code:
curl -X POST 'http://api.sc2ranks.com/v2/characters/search' -d 'name=Wodan&bracket=1v1&league=gold&expansion=hots&rank_region=global&api_key='<api_key>'
Hoping for an easy ride I created a small script that performs a HTTP-GET request on the API returning the base statistics for every in-game user. This URL can ofcourse be directly formed in the browser:
http://api.sc2ranks.com/v2/characters/eu/1616021?api_key=<api_key>
This is handled in my code in the following way (note: $url is the above URL and $this->session is the initialization of curl):
curl_setopt($this->session,CURLOPT_URL, $url);
curl_setopt($this->session,CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->session,CURLOPT_HEADER, true);
if( !$result = curl_exec($this->session) )
exit("cURL Error: " . curl_error($this->session));
else
return $result;
The problem
Well on my way I decided to use the more advanced functions of the API to get more detailed information on the member. This is however where the confusion starts. Looking back at the above original curl post in the terminal, it shows two options. The -X (request) and the -d (post data). Figuring the first would be the URL make the HTTP-POST request to and the later being the data, I came up with the following example:
$url = "http://api.sc2ranks.com/v2/characters/search/";
$data = "league=all&rank_region=global&expansion=hots&bracket=1v1&name=Wodan?api_key=<my_key>";
curl_setopt($this->session, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($this->session, CURLOPT_POSTFIELDS, $data);
curl_setopt($this->session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->session, CURLOPT_HTTPHEADER, array(
'Content-Type: text/html',
'Content-Length: ' .strlen($data))
);
if( !$result = curl_exec($this->session) )
exit("cURL Error: " . curl_error($this->session));
else
return $result;
I've also tried to pass the above through as JSON format.
The output As a result I only get the following as a server response:String '{' was not found in 'HTTP/1.1 404 Not Found Server: nginx Date: Sun, 17 Nov 2013 22:14:03 GMT Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: close Status: 404 Not Found X-Request-Id: 700726570451c891d48862edfc8545fb X-Runtime: 0.009002 X-Rack-Cache: invalidate, pass '
What I think is going wrong Most likely I'm not forming the request right to the server or I need to target a specific file, other then they have documented it. I have found two similar questions here concerning POST's with Curl. But they were of little help to me and I feel that this might help more people out.
Hopefully someone in this community has some more experience with curl or the actual API.

use the following code
$apiParams = array ("league" => "all",
"rank_region" => "global",
"expansion" => "hots",
"bracket" => "1v1",
"name" => "Wodan",
"api_key" => "<my_key>");
$Url = "http://api.sc2ranks.com/v2/characters/search";
$curlHandler = curl_init($Url);
curl_setopt($curlHandler, CURLOPT_POST, true);
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $apiParams);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandler, CURLOPT_HTTPHEADER, array(
'Content-Type: text/html',
'Content-Length: ' .strlen($data))
);
$statusCode = curl_exec($curlHandler);
curl_close($curlHandler);

Hello people and thank you all for your help! I have solved the problem on my own now, but I had to scroll through the PHP manual for setopt itself. This is the following code that works:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://api.sc2ranks.com/v2/characters/search");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,"name=Wodan&bracket=1v1&league=gold&expansion=hots&rank_region=global&api_key=<my_key>");
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec ($ch);
curl_close ($ch);
Note the commented out line above. The manual say's the following about CURLOPT_RETURNTRANSFER:
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
Since this example is not a HTTP GET-request but a HTTP POST-request there will be no direct string collected from the URL. When set to false it will collect any output that gets returned.
My interpretation of the manual might be wrong, but this has solved the issue at least. I hope this will help other people. Thanks everyone for your help.

Related

How can I convert data from POSTMAN into PHP Curl Request?

I have an API in postman. I want to create a CURL Request and get proper response with it. This is my POSTMAN API.
I am successfully getting this response with it.
"{\"Request\":{\"state\":\"Manama\",\"address\":\"406 Falcon Tower\",\"address2\":\"Diplomatic Area\",\"city\":\"Manama\",\"country\":\"BH\",\"fullname\":\"Dawar Khan\",\"postal\":\"317\"},\"Response\":{\"status\":\"Success\",\"code\":100,\"message\":\"Address is verified\"}}"
Now I want to use this API Call inside my PHP Code. I used this code.
$data = array(
'Request' => 'ValidateAddress',
'address' => test_input($form_data->address),
'secondAddress' => test_input($form_data->secondAddress),
'city' => test_input($form_data->city),
'country' => test_input($form_data->country),
'name' => test_input($form_data->name),
'zipCode' => test_input($form_data->zipCode),
'merchant_id' => 'shipm8',
'hash' => '09335f393d4155d9334ed61385712999'
);
$data_string = json_encode($data);
$url = 'myurl.com/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode($result, true);
echo '<pre>';print_r($json_result);echo '</pre>';
But I can't see my $json_result. It just echoes <pre></pre> in the view. Can anyone guide me? Thanks in advance. I want to get my Response.
UPDATE
I used curl_error and it gives me the following error.
Curl error: SSL certificate problem: self signed certificate in certificate chain
It is Very Simple Just Click on Code you will get the code in php.
you will get the code in many language like php,java,ruby,javascript,nodejs,shell,swift,pythom,C# etc.
Answer updated as per updated question.
There are two ways to solve this issue
Lengthy, time-consuming yet clean
Visit URL in web browser.
Open Security details.
Export certificate.
Change cURL options accordingly.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/BuiltinObjectToken-EquifaxSecureCA.crt");
Quick but dirty
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
We are configuring cURL to accept any server(peer) certificate. This isn’t optimal from a security point of view.
Excerpt from very detailed and precise article with screenshots for better understanding. Kindly refer the same before actually implementing it in production site.

PHP Curl results into invalid json

I want to send json data via PUT to a REST service using the following php code:
$data = '{"api_key":"my-api-key","post":{"exception":["2015-04-10T11:09:51+00:00 ERR (3):\\nexception 'Exception' with message 'a simple exception' in \/private\/var\/www\/index.php:1\\nStack trace:\\n#0 {main}"],"access":["::1 - - [10\/Apr\/2015:13:08:17 +0200] \"GET \/index.php HTTP\/1.1\" 200 19039"]}}';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
$response = curl_exec($curl);
As you can see I send valid json (validated by http://jsonlint.com/). On the side of the service I get the following json:
{"api_key":"my-api-key","post":{"exception":["2015-04-10T11:09:51+00:00 ERR (3):\\\\nexception \'Exception\' with message \'a simple exception\' in \\/private\\/var\\/www\\/index.php:1\\\\nStack trace:\\\\n#0 {main}"],"access":["::1 - - [10\\/Apr\\/2015:13:08:17 +0200] \\"GET \\/index.php HTTP\\/1.1\\" 200 19039"]}}
Validating this says I got a parse error. And this seems correct as I can't understand why further escaping is done like \\\\n. What am I doing wrong here?
I doubt that this is a valid use of a PUT and should be a POST but that is just a technicality. If you can, make it a POST. The PUT is likely the root of the issue.
The CURLOPT_PUT uses CURLOPT_INFILE and CURLOPT_INFILESIZE
The URLOPT_CUSTOMREQUEST should work fine but it appears you have some RFC 3986 escaping going on for some unexplainable reason.
You may want to use rawurldecode ( ) on the Service Side.
This will give you (appears correct but I'm not the guy to verify):
{"api_key":"my-api-key","post":{"exception":["2015-04-10T11:09:51+00:00 ERR (3):\\nexception 'Exception' with message 'a simple exception' in \/private\/var\/www\/index.php:1\\nStack trace:\\n#0 {main}"],"access":["::1 - - [10\/Apr\/2015:13:08:17 +0200] \"GET \/index.php HTTP\/1.1\" 200 19039"]}}
Disclaimer: I have never used curl to POST Content-Type: application/json data.
You need to look at your Request Header and maybe Response. It would be interesting to see if you get the proper PUT Response.
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
Check your Request Header Content-Type
To get the headers:
The response Header will be in the returned transfer.
The Request Header will be in curl_getinfo()
The curl info will also include the HTTP Response Status. Which for a PUT should be 201 or 301 but not important.
$data = curl_exec($ch);
$skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$responseHeader = substr($data,0,$skip);
$data= substr($data,$skip);
$info = var_export(curl_getinfo($ch),true);
echo $responseHeader . $info . $data;
If you still want to send the json without curl escaping it I have some thoughts on that. but there is probably a post on that subject here somewhere.

PHP HTTP POST Request

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.

How to send and receive JSON data between two servers via php

Obviously I am not using the right keywords in my searches or am not understanding what others have written in blogs or forums, et al.
Looking for information on passing data between two servers. The data will be preferably contained within a JSON array.
If you know of someone who has written a blog fully encompassing this I would really like a chance to read it. Otherwise could you offer some thoughts?
More detailed:
As a user visits a page a PHP function will be called and some data will be "packaged up" in a JSON array and then a POST command to the other server. The second server after receiving the POST will do some processing and then "package up" some data and return it in a JSON array. Then the user will be presented with the results.
With the following I am receiving a HTTP 200 response. Just no data.
SITE 1:
$data_string = json_encode(array('user_id'=>123));
$ch = curl_init('http://site2.dev/retrieve');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);
$status = curl_getinfo($ch);
curl_close($ch);
$result = json_decode($result);
SITE 2:
public function retrieve() {
return json_encode(array('some'=>'456'));
}
The Json array was chosen as it can be encrypted and yes HTTPS will be used in the final environment.
Both servers will have Laravel 4 as the PHP Framework.
Thank you for your thoughts and comments.
Add this:
curl_setopt($ch, CURLOPT_HEADER, 0);
and put quotes on content-length:
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type: application/json','"Content-Length: ' . strlen($data_string) . '"'));

Adding events via places return 404 error:

Please excuse my terminology if I get anything wrong, I'm new to Google API
I'm trying to add events via the Places API, for a single venue (listed under the bar category). I've followed the instructions here:
https://developers.google.com/places/documentation/actions?utm_source=welovemapsdevelopers&utm_campaign=places-events-screencast#event_intro
and this is the URL I am posting to (via PHP)
https://maps.googleapis.com/maps/api/place/event/add/format?sensor=false&key=AIzaSyAFd-ivmfNRDanJ40pWsgP1 (key altered)
which returns a 404 error. If I have understood correctly, I have set the sensor to false as I am not mobile, and created an API key in Google apis, with the PLACES service turned on.
Have I missed a vital step here, or would a subsequent error in the POST submission cause a 404 error? I can paste my code in but I thought I'd start with the basics.
Many thanks for your help, advice and time. It's very much apprecciated.
I've added this line to my CurlCall function which I believe should specify a POST, and the result is still the same.
curl_setopt($ch, CURLOPT_POST, 1);
so the whole functions reads
function CurlCall($url,$topost)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $topost);
$body = curl_exec($ch);
curl_close($ch);
echo $body;
echo '<br>';
echo 'URL ' . $url;
echo '<br>';
return $body;
}
Are you sure that you are using the POST method and not GET?
You need to specify the format of your request in the URL by changing the word format to either json or xml depending on how you are going to structure and POST your request.
XML:
https://maps.googleapis.com/maps/api/place/event/add/xml?sensor=false&key=your_api_key
JSON:
https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=your_api_key

Categories