Create HTTP GET Header Request - php

I am using php and I want to create a HTTP request to access some API data. I have a document that says, I need to place the following request
GET /abc/api/Payment HTTP/1.1
Content-Type: application/x-www-form-urlencoded
X-PSK: [App Key]
X-Stamp: [UTC Timestamp]
X-Signature: [HMACSHA256 base 64 string]
Body:
var1, var1
I have app key, I can get UTC Timestamp and I can create signature. I am not sure how to start creating this request? I am using codeingiter. If someone can help with example to set the header and body?
I also tried this url https://www.hurl.it/ to place requests but can't make it work. Any suggestions?

You want to use cURL's CURLOPT_HTTPHEADER option.
http://php.net/manual/en/function.curl-setopt.php
This should get you started
function request($url) {
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"X-PSK: [App Key]",
"X-Stamp: [UTC Timestamp]",
"X-Signature: [HMACSHA256 base 64 string]"
),
CURLOPT_FOLLOWLOCATION => true
);
curl_setopt_array($ch, $curlOpts);
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) die(curl_error($ch));
curl_close($ch);
return $answer;
}

Related

How to use curl php

I desperately want to use an API that asks curl. I do not know anything at all. So I teter to document myself, but I do not understand everything.
Here is what the API says:
All requests must be provided with unique API keys, which you can generate in dashboard. X-API-ID (public) and X-API-KEY (private) parameters. For example:
curl -L http://www.coinimp.com/api/v2/hashes
-H 'X-API-
ID:7e26bb94aa2ce44e6e16aca6ae6d28c7f0157b5ccd7a82f86bbbe8d835effd71'
-H 'X-API-
KEY:5112486af64b2f97bd3742c4153cee32452549491480cfd164b336720b82a84d'
Here is my code:
$curl = curl_init();
$opts = array(
CURLOPT_URL => 'http://www.coinimp.com/api/v2/hashes',
CURLOPT_HEADER => array(
'X-API-
ID:0cd6929b8e34e2cc686eb50bef6a909c4898125b5105221fbfe48a43b038d9ff',
'X-API-
KEY:61dbf2d44abd138bad67c7876dcac0f58b2f08c8bbb91108c7c0984fe7b5f207',
)
);
curl_setopt_array($curl, $opts);
$response = json_decode(curl_exec($curl), true);
print_r($response);
Here is my result:
HTTP/1.1 301 Moved Permanently Date: Sat, 16 Feb 2019 20:19:44 GMT Transfer-Encoding: chunked Connection: keep-alive Cache-Control: max-age=3600 Expires: Sat, 16 Feb 2019 21:19:44 GMT Location: https://www.coinimp.com/api/v2/reward Server: cloudflare CF-RAY: 4aa2b5fd8a25c83d-AMS 1
Please can you help me ?
CoinImp is an absolute mess; I worked with them briefly on a client project and quickly came to dislike their service. You're receiving a 301 response, which indicates that the resource you're requesting is no longer at that address. In the response it appears to give you the new endpoint:
https://www.coinimp.com/api/v2/reward
I would try reformatting your request towards that endpoint. Otherwise, this would be a question for CoinImp support.
I don't know your problem, but i suggest use to use Postman Api Development Environment.
https://www.getpostman.com/
You should enter URL where you will make the request, username, password and additional parameters specified by API provider.
You can test API also you can generate script in different programming languages without writing a single row of code.
Hope this helped you.
Try this:
Replace WEBSITE-ID with the ID you used for miner script.
And replace PUBLIC-ID and SECRET-ID, also USER-ID.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.coinimp.com/api/v2/user/balance?site-key=WEBSITE-ID&user=USER-ID",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"x-api-id: PUBLIC-ID",
"x-api-key: SECRET-ID"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
Good luck.

Google Analytics request validates correctly, but returns error when sent from CURL

I'm sending the following request to Google Analytics:
http://www.google-analytics.com/collect?v=1&tid=UA-72579327-1&cid=61baecac-8f8c-4dce-bf07-a7efa24a4e47&t=transaction&ti=qcY6pvpWGmP9fHyi&tr=10.00&cd1=Acme Racing&cd2=http://www.domain.co.uk/affiliate/idevaffiliate.php/id=314&tid1=12044762460674420322&url=http://www.nitrotek.co.uk&cd3=A1&cd4=Upgrades&cd5=Acme-Tech &cd6={device}&cd7=&cd8=0&cd9=&cd10=&cd11=&cd12=Nitrotek DSA&cd13=g&cd14=50&cd15=1&cd16=85&cd17=12044762460674420322&cd18=&cd19=http://www.domain.co.uk&cd20=61baecac-8f8c-4dce-bf07-a7efa24a4e47&gclid=
When you go to Google's hit builder and validate the request, it comes out valid.
However, when I send the same request through CURL POST, I just get "400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know.".
POST is the correct method for this request (though I have tried GET just in case) and the Content-Length header is the length of the sent data (string). Here is the code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $transaction_url, //the same URL string given above
CURLOPT_POST => 1,
CURLOPT_USERAGENT => 'cURL Request'
));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Length: '.strlen($transaction_url) //length of URL string
));
$trans_resp = curl_exec($curl);
var_dump($trans_resp);
curl_close($curl);

Making GET requests using PHP

I am trying to make a simple GET request to the yesmail api, i have the url which i can paste directly in the browser and it displays the correct information, and also if i add the following code as shown in the brief documentation in the Firefox RESTClient i get the correct response:
GET https://services.yesmail.com/enterprise/subscribers?email=karina#email.co.uk HTTP/1.1
Accept-Encoding: gzip,deflate
User-Agent: Jakarta Commons-HttpClient/3.1
Authorization: Basic xxxxxxxxxxxxx
Host: services.yesmail.com
However, when trying to connect using CURL, i am getting nothing, no HTTP response at all and just a blank page. I am not sure what i am doing wrong? This is what i have:
$url = "https://services.yesmail.com/enterprise/subscribers?email=karina#email.co.uk";
$header[] = "Accept-Encoding: gzip, deflate";
$header[] = "User Agent: Jakarta Commons-HttpClient/3.1";
$header[] = "Authorization: Basic xxxxxxxxxxxxx";
$header[] = "Host: services.yesmail.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header );
curl_setopt($ch, CURLOPT_USERPWD, 'xxxxx:xxxxxxxxxx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$response = (curl_exec($ch));
print_r($response);
curl_close($ch);
Am i wrong in thinking that the information i put in to the RESTClient goes into the headers in CURL? This is the first time i have been working with API's so any help appreciated.
update
When using the function file_get_contents i get the correct response(which for the GET method is just a URL with my unique subscriber number):
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode("*******:********")
)
));
$data = file_get_contents('https://services.yesmail.com/enterprise/subscribers?email=karina#email.co.uk', false, $context);
echo $data;
However i really want to get the CURL method working as i will want to be able to add a subscriber.
I actually work at Yesmail so I may be able to help you out here.
Give the following code a try (be sure to replace the your-auth-here text with your base64 encoded authentication info and to set the appropriate URL in $ym_api_url)
<?php
// Set the HTTP headers needed for this API call.
$http_headers = array(
"Authorization: Basic your-auth-here",
"Accept: application/json",
"Connection: close", // Disable Keep-Alive
"Expect:" // Disable "100 Continue" server response
);
// URL Endpoint of the API to be called.
$ym_api_url = 'https://services.yesmail.com/enterprise/subscribers?email=karina#email.co.uk';
$curl_hdl = curl_init();
$curl_options = array(
CURLOPT_VERBOSE => 1, // Verbose mode for diagnostics
CURLOPT_HEADER => TRUE, // Include the header in the output.
CURLOPT_HTTPHEADER => $http_headers, // HTTP headers to set
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, // Use basic authentication.
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, // Bitmask of protocols libcurl may use in this transfer
CURLOPT_RETURNTRANSFER => TRUE, // Return result as return value of curl_exec()
CURLOPT_URL => $ym_api_url, // URL to POST data to
);
curl_setopt_array($curl_hdl, $curl_options);
// Make the API call
$response = curl_exec($curl_hdl);
// Get the http response code
$http_response_code = curl_getinfo($curl_hdl, CURLINFO_HTTP_CODE);
curl_close($curl_hdl);
echo PHP_EOL . "INFO: HTTP Response Code was: " . $http_response_code . PHP_EOL;
if ( $response === false )
{
echo PHP_EOL . "ERROR: curl_exec() has failed." . PHP_EOL;
}
else
{
echo PHP_EOL . "INFO: Response Follows..." . PHP_EOL;
echo PHP_EOL . $response;
}
?>
The CURLOPT_VERBOSE => 1 option will output additional diagnostic info. Note any issues there to see if that points to a specific problem. Once you have the issue(s) worked out you can remove or disable those options.
Also, remember you can always contact your Yesmail Account Manager and request assistance.
So you get the $response, but don't do anything with it.
There is no line in your code which is expected to display anything.
Update: I see you updated your question.
A very important rule: always check the return value of API calls.
curl_exec() signals an error by returning FALSE, if that's the case, check it with curl_error($ch).

php file get contents with post data [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Drupal login via Rest server
I have been using this code for file get contents with post data but receiving an error
Warning: file_get_contents(http://50.116.19.49/rest/user/login.json): failed to open
stream: HTTP request failed! HTTP/1.0 406 Not Acceptable: Unsupported request content type
application/x-www-form-urlencoded in C:\xampp\htdocs\post.php on line 20
My code is
<?php
$postdata = http_build_query(
array(
'var1' => 'myuser',
'var2' => 'pwd'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://50.116.19.49/rest/user/login.json', false,
$context);
?>
Can anybody help in this Thanks in advance.
we can use curl instead of function file_get_contents($request);
Here is the code of curl :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$xml_response = curl_exec($ch);
where $request is your url.
This particular server, as it seems, expects to see JSON in the POST data when you call /login.json, so you should rewrite a few things in your code.
Change the $postdata construction:
$postdata = json_encode(array(
'var1' => 'myuser',
'var2' => 'pwd'
));
Change the Content-Type header:
$opts = array('http' => array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $postdata
));
file_get_contents returns FALSE on error with the HTTP stream wrapper as well. An error means any error condition with the HTTP response, for example a HTTP status code from the 400 range like 406 Not Acceptable: Unsupported request content type in your case.
You can disable the "FALSE on Error" behavior by setting the ignore_errorsHTTP context option to TRUE:
'ignore_errors' = TRUE,
You will then get the response body of the request as the result in error cases, too.
To obtain the status code itself you can make use of the special $http_response_header variable.
For a discussion of these settings and how to parse response headers, please see HEAD first with PHP Streams. However in your case the response body might already contain more information about the problem.
In your specific problem you need to double check that the encoding of the request is supported by the server. As I don't know your server, I can not say much about that. The reference to the error code might shed some light for you. There seems to be a problem with the Content-type: application/x-www-form-urlencoded you are using.
For example as other clever folks on this site have told me, that endpoint is Drupal. If so, the following was suggested in a similar question:
You have to enable application/x-www-form-urlencoded content type of your service endpoint.
Do as follows: Services -> Edit Resources -> select tab "Server" -> enable "application/x-www-form-urlencoded" and that's it.
Hopefully this is of help to you.

add headers to file_get_contents in php

I am completely new PHP and want a client program to call an URL web service.I am using file_get_content to get the data.How do add additional headers to the request made using file_get_content.
I also was thinking of using cURL. I wanted to know how cURL can be used to do a GET request.
You can add headers to file_get_contents, it takes a parameter called context that can be used for that:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => "Host: www.example.com\r\n" .
"Cookie: foo=bar\r\n"
)
));
$data = file_get_contents("http://www.example.com/", false, $context);
As for cURL, the basic example from the PHP manual shows you how to perform a GET request:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>

Categories