Making GET requests using PHP - 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).

Related

PHP cURL return blank page

I had been using PHP curl to get the contents of a file, hosted on a different server. The file can easily be opened on a browser like Chrome etc., but with cURL, it always returns a blank page.
The file is hosted on an Nginx server and even miniproxy.php fails to get contents. Instead, it returns 406 not acceptable. I tried using the HTTP spy extension to monitor the request sent and found the following header:
Upgrade-Insecure-Requests:1
I tried sending the same header along With other headers, but in vain. Still, I couldn't rectify my mistake. On the Internet, I found the zalmos proxy which was able to get the contents of the file. The curl code I wrote is attached below.
$url = "http://smumcdnems01.cdnsrv.jio.com/jiotv.live.cdn.jio.com/" . $ch . "/" . $ch . "_" . $q . ".m3u8" . $tok;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"User-Agent: agent",
"lbcookie: 300",
"devicetype: 1",
"os: android",
"appkey: 1111111",
"deviceId: device id",
"uniqueId: unique id",
"ssotoken: any token",
"Upgrade-Insecure-Requests: 1",
"Host: example.com",
"Connection: keep-alive",
"X-Chrome-offline: persist=0 reason=reload",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding: gzip, deflate, sdch",
"Accept-Language: en-GB,en-US;q=0.9,en;q=0.8",
"subscriberId: any id",
);
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 $url;
echo $resp;
I believe that any part is missing in my code which is posing a problem. How can this be rectified?
Check your URL. Curl must give you the response. If it's hit the target URL, either the target URL is not responding to anything when sending the request.
You may be trying to access a websocket. Try to simulate with Postman to get more information.

How do I use Oauth2 using cURL and PHP

I can't get the folling script to work:
I'm using an api called swiftdil. Their example is as follows:
Example request:
curl -X POST https://sandbox.swiftdil.com/v1/oauth2/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-u 'your_username:your_password'
Example output:
{
"access_token":"your_access_token",
"expires_in": 3600,
"refresh_expires_in": 1800,
"refresh_token": "your_refresh_token",
"token_type": "bearer",
"not-before-policy": 0,
"session_state": "your_session_state"
}
So the url I've to submit my credentials to is https://sandbox.swiftdil.com/v1/oauth2/token
I've tried the following code:
// Api Credentials
$url = 'https://sandbox.swiftdil.com/v1/oauth2/token';
$username = "my_username";
$password = "my_password";
// Set up api environment
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:
application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" .
$password);
// Give back curl result
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$curl_error = curl_error($ch);
curl_close($ch);
print_r($output);
print_r($info);
print_r($curl_error);
?>
The script is giving me back the following result:
HTTP/1.1 400 Bad Request Server: nginx/1.13.8 Date: Tue, 15 May 2018 09:17:26 GMT Content-Type: text/html Content-Length: 173 Connection: close
400 Bad Request.
Am I missing something? I do fullfill the needs of the example given above right? I do make a postcall, give all the credenatials as asked, but still can't get anything back.
I am not a PHP developer, I mostly do JavaScript. When I integrate with other REST services I tend to use Postman (https://www.getpostman.com/).
Try the following:
Attempt to successfully connect with the API using Postman (should be relatively straightforward).
When successful, Postman has the ability to generate PHP code automatically, which you can then copy and paste. Works like a charm with JavaScript, don't see why it will be any different with PHP.
I just filled in the details in postman based on what you provided:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://sandbox.swiftdil.com/v1/oauth2/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ=",
"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 {
echo $response;
}
Please note, 'Authorization: Basic' can be used as basic authorization mechanism instead of 'Bearer' (it should work too). So replace 'bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ' with the base64 encoded string 'username:password' (use actual username and password).
You also need to set the curl post fields by setting the below option as per your data.
"curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
))";
If still not work, you can find the curl error as :
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}

Why is my POST with cURL not returning JSON correctly?

In PHP, I'm trying to retrieve the url for a specific page in DocuSign that constantly refreshes. The POST to retrieve this url is in the form:
POST http://demo.docusign.net/restapi/{apiVersion}/accounts/{accountId}/envelopes/{envelopeId}/views/recipient
This should return a json file in the form:
{
"url": "example.example.com"
}
However, I am extremely new to using PHP and POST methods and don't believe I'm doing this correctly. The API explorer for this method in particular is here. I am using cURL methods to make this request. Here is my code ($recipient,$account_id,$access_token are found accurately within another file):
$url = "http://demo.docusign.net/restapi/v2/accounts/$account_id
/envelopes/$envelope_id/views/recipient";
$body = array("returnUrl" => "http://www.docusign.com/devcenter",
"authenticationMethod" => "None",
"email" => "$recipient",
"userName" => "$recipient");
$body_string = json_encode($body);
$header = array(
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: '.strlen($body_string),
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body_string);
$json_response = curl_exec($curl);
$response = json_decode($json_response, true);
var_dump($response);
I am able to get the correct return on the API explorer, but not when making the request with PHP. I believe this is due to the fact that I am not incorporating the $header or $body correctly, but at this point I am just not sure.
ADDED: This is the raw output for the request when correctly running the method on the API Explorer:
Accept: application/json
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,fa;q=0.6,sv;q=0.4
Cache-Control: no-cache
Origin: https://apiexplorer.docusign.com
Referer: https://apiexplorer.docusign.com/
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Authorization: Bearer fGehcK7fkRvFguyu/7NGh01UUFs=
Content-Length:
Content-Type: application/json
This is the JSON request being formed in my code:
{
"returnUrl":"http:\/\/www.docusign.com\/devcenter",
"authenticationMethod":"Password",
"email":"example#example.com",
"userName":"example#example.com",
"clientUserId":"4c6228f4-fcfe-47f9-bee1-c9d5e6ab6a41",
"userId":"example#example.com"
}
You are not hitting a valid DocuSign URL in your cURL code. Right now you are sending requests to:
http://demo.docusign.net/apiVersion/v2/accounts/{accountId}/envelopes/{envelopeId}/views/recipient
Instead of "apiVersion" it should be "restApi" like this:
http://demo.docusign.net/restapi/v2/accounts/{accountId}/envelopes/{envelopeId}/views/recipient
We can't send post fields, because we want to send JSON, not pretend to be a form (the merits of an API which accepts POST requests with data in form-format is an interesting debate). Instead, we create the correct JSON data, set that as the body of the POST request, and also set the headers correctly so that the server that receives this request will understand what we sent:
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
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);
All these settings are pretty well explained on the curl_setopt() page, but basically the idea is to set the request to be a POST request, set the json-encoded data to be the body, and then set the correct headers to describe that post body. The CURLOPT_RETURNTRANSFER is purely so that the response from the remote server gets placed in $result rather than echoed. If you're sending JSON data with PHP, I hope this might help!
I know this question was asked more than 3 years ago, but this may help someone who finds this question because they are having the same problem. I do not see a cURL option that will decode the response in your code. I have found that I need to use the cURL option CURLOPT_ENCODING like this: curl_setopt($ch,CURLOPT_ENCODING,""); According to the PHP manual online, it says, 'CURLOPT_ENCODING - The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent.' You can find this option at https://www.php.net/manual/en/function.curl-setopt.php. I hope this helps save someone from having a headache.

Create HTTP GET Header Request

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;
}

Sending Custom Header with CURL

I want to send a request to a web service via an API as shown below, i have to pass
a custom http header(Hash), i'm using CURL, my code seems to work but I'm not getting
the rigth response, I'm told it has to do with the hash value, though the value has
been seen to be correct, is there anything wrong with the way I'm passing it or with
the code itself.
<?php
$ttime=time();
$hash="123"."$ttime"."dfryhmn";
$hash=hash("sha512","$hash");
$curl = curl_init();
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Hash:$hash'));
curl_setopt ($curl, CURLOPT_URL, 'http://web-service-api.com/getresult.xml?clientid=456&time=$ttime');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec ($curl);
if ($xml === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($xml);
echo htmlspecialchars("$xml", ENT_QUOTES);
?>
If you need to get and set custom http headers in php, the following short tutorial is really useful:
Sending The Request Header
$uri = 'http://localhost/http.php';
$ch = curl_init($uri);
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array('X-User: admin', 'X-Authorization: 123456'),
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_VERBOSE => 1
));
$out = curl_exec($ch);
curl_close($ch);
// echo response output
echo $out;
Reading the custom header
print_r(apache_request_headers());
you should see
Array
(
[Host] => localhost
[Accept] => */*
[X-User] => admin
[X-Authorization] => 123456
[Content-Length] => 9
[Content-Type] => application/x-www-form-urlencoded
)
Custom Headers with PHP CGI
in .htaccess
RewriteEngine On
RewriteRule .? - [E=User:%{HTTP:X-User}, E=Authorization:%{HTTP:X-Authorization}]
Reading the custom headers from $_SERVER
echo $_SERVER['User'];
echo $_SERVER['Authorization'];
Resources
http://www.omaroid.com/php-get-and-set-custom-http-headers/
How can I get PHP to display the headers it received from a browser?
'Hash:$hash' should be either "Hash: $hash" (double quotes) or 'Hash: '.$hash
The same goes for your URL passed in CURLOPT_URL

Categories