The following code runs without any errors, however it doesn't return anything.
If I paste it into my browser it returns the information I'm looking for, I can also replace it with another URL and it works perfectly.
$ch = curl_init();
$url = 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=Somerset&structure={"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}';
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
$decode =json_decode($resp);
print_r($decode);
curl_close($ch);
You can use following generated code by the postman
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.coronavirus.data.gov.uk/v1/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS =>'{"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
This code is worked. Reason is encoding of received content.
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ( $ch === false ) {
throw new RuntimeException( 'failed to initialize' );
}
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL,
'https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=Somerset&structure={"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}' );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Solution is here. Response is the compressed content which your curl failed to detect. Empty encoding means to handle any type of encoding. It should solve your issue.
curl_setopt($ch, CURLOPT_ENCODING, '');
$content = curl_exec( $ch );
curl_close( $ch );
if ( $content === false ) {
throw new RuntimeException( curl_error( $ch ), curl_errno( $ch ) );
}
/* Process $content here */
$decode = json_decode( $content );
var_dump( $decode );
// Close curl handle
curl_close( $ch );
} catch ( RuntimeException $e ) {
trigger_error(
sprintf(
'Curl failed with error #%d: %s',
$e->getCode(),
$e->getMessage()
),
E_USER_ERROR
);
}
Related
I'm trying to fetch data from API, but no data returns.
I try the API request in postman and it's working but in my php code nothing gets returned.
$uri = 'https://example.com';
$opts = array(
'http' => array(
'method'=>'POST',
'header'=>'Content-Type: application/x-www-form-urlencoded',
)
);
$context = stream_context_create($opts);
$result = file_get_contents($uri, false, $context);
print $result;
or using curl
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
the error is
file_get_contents(https://example.com): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required
Note: the response size in postman is 9.83, is this maybe an issue?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
The issue has been solved by add Content-Length: 0 in the header
I'm having difficulty obtaining an access token from the token endpoint using PHP (https://developer.tdameritrade.com/authentication/apis/post/token-0)
Particularly, I'm getting the following error:
{ "error":"Failed to resolve API Key variable request.header.un" }
My request, using PHP, is:
$url = 'https://api.tdameritrade.com/v1/oauth2/token';
$client_id = $customer_key ;
$redirect_uri = $redirect_URL;
$myvars = array("grant_type" => "authorization_code"
, "access_type" => "offline"
, "client_id" => $client_id
, "redirect_uri" => $redirect_URL
, "code" => "$code");
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $ch, CURLOPT_VERBOSE, 1);
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded; charset=utf-8'
));
$response = curl_exec( $ch );
echo "<br>token = '$response'\n";
}
Thanks!
OK, I finally got a working PHP script that authenticates into the TD API and obtains account information. I'd like to share it with everyone because I couldn't figure out how to get it working after almost three months. A special thanks to Ninet3 for helping me out. You can direct questions to his Fiverr profile (https://www.fiverr.com/ninety3)
$redirect_URL = 'https://YourURL.com';
$redirect_URL = urlencode($redirect_URL);
$customer_key = 'XXXXXXXXXXXXXXXXXXXX';
$account_number = '1234567890';
$url_endpoint = 'https://auth.tdameritrade.com/auth?response_type=code&redirect_uri='.$redirect_URL. '&client_id='.$customer_key.'%40AMER.OAUTHAP';
if(NULL === #$_GET['code']) {
header("Location: $url_endpoint");//open TD website to get tokens
}
if($_GET['code'] !== '') {
$code = $_GET['code'];
$code = urlencode($code);
if($code){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.tdameritrade.com/v1/oauth2/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0, CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded',
),
CURLOPT_POSTFIELDS => 'grant_type=authorization_code&refresh_token=&access_type=offline&code='.$code.'&client_id='.$customer_key.'&redirect_uri='.$redirect_URL,
));
$response = curl_exec($curl);
curl_close($curl);
$response = (json_decode($response, true));
echo '<pre>';
echo 'access_token: <br>';
print_r($response );
//Get account information
if(#$response['access_token'] !== null){
$acc = $account_number;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.tdameritrade.com/v1/accounts/'.$acc,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '.$response['access_token'],
),
));
$response = curl_exec($curl);
curl_close($curl);
echo '<pre>'.$response;
}else{
echo 'unable to get access token'; exit;
}
}
else{
echo 'No Code Found'; exit;
}
}else{
echo 'No Code Found'; exit;
}
You'll need to store the token in a database and refresh to get a new one after the time expires.
I found this page when I got the exact same error message. I finally figured it out after quite a few tries and stepping away a few times. The biggest change from what you've posted is that when you use the header:
"Content-Type: application/x-www-form-urlencoded"
which TD wants for this API, you need to make the $myvars array into a string like the following:
$myvars = "grant_type=authorization_code&access_type=offline&code=".$code."&client_id=".$client_id."&redirect_uri=".urlencode($redirect_uri);
The other note here is the urlencode function to help url encode the string. It talks about that in the 'Notes' section of this page:
https://www.php.net/manual/en/function.curl-setopt.php
I am hitting my content server which sends multipart data.
When server response is small ( < 40KB ) , I am getting full response data in $response
string. But when server response data is large ( > 112KB) its getting trimmed to 48KB
and my whole multipart data parsing is failing.
What should I do to get the whole 112KB data in $response string ?
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $this->url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_param);
$response = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
parseData($response);
Please help, what i am doing wrong here.
Please help me i am having some trouble.
What i want to do is integrate moneybooker in my website.
I studied the "Merchant Integration Manual version 6.17" in 2.3.2 Topic where i have to create and get a SESSION_ID form skrill server by sending payment parameters by post and get the SESSION_ID this session will hold my transaction information like amount and my account.
By using below code i can't retrieve the SESSION_ID from their server.
$url = "https:www.moneybookers.com/app/payment.pl";
$post_data = array (
"prepare_only" => 1,
"amount" => 10,
"currency" => 'USD',
"detail1_description" => "Description",
"detail1_text" => "Text",
"pay_to_email" => "****my**accoutn#yahoo.com"
);
$head = get_web_page($url, $post_data);
echo "<pre>";
print_r($head);
echo "</pre>";
function get_web_page( $url, $post_data )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//we are doing a POST request
curl_setopt($ch, CURLOPT_POST, 1);
//adding the post variables to the request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
The above code works for other sites but not for moneybooker.
But when i submit simple html form, session id is created and shown but i am not being redirected to my site !!
Try adding cookies support
$fh = fopen("cookies.txt", "a+") or die("Can't open file!");
fclose($fh);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
When you set CURLOPT_POSTFIELDS with an array, the request will be sent as multipart/form-data, try changing that line to:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
I have the following JSON code:
{"username":"user1","password":"123456"}
That I need to pass to a url, lets say: http://api.mywebsite.com
I'm an extreme php newb, so I've been following a curl tutorial, but here is my current PHP code:
<?php
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
?>
You might want to look into the CURLOPT_POSTFIELDS AND CURLOPT_POST options. These allow you to do a POST request and pass the data set into the CURLOPT_POSTFIELDS in the request.
Something in the lines of this:
$body = 'bar=1&foo=2&baz=3';
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
When you want to use normal GET Params:
$jsonString ='{"username":"user1","password":"123456"}';
$params = json_decode($jsonString);
$getParams = '';
$first = true;
foreach ($params as $key => $param){
if ($first){
$getParams .= '?';
$first = false;
} else{
$getParams .= '&';
}
$getParams .= $key .'=' .$param;
}
echo $getParams;
get_web_page($url . $getParams);