While checking the URL: https://i2.wp.com/jarek-kefir.org/wp-content/uploads/2019/04/pożar-katedry-notre-dame.jpg?ssl=1
I have result status code 400...
This is my function:
public function callAPI($url)
{
$curl = curl_init();
error_log('Checking url: ' . $url);
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//'APIKEY: 111111111111111111111',
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
// EXECUTE:
$result = utf8_decode(curl_exec($curl));
$result = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result);
if (!$result) {
error_log('Connection Failure ' . $result . ' for url: ' . $url);
}
// Check if any error occurred
$error_msg = '';
$error_number = curl_errno($curl);
$error_info = curl_error($curl);
$info = curl_getinfo($curl);
$httpCode = $info['http_code'];
$request_ok = $httpCode == 200 || $httpCode == 201 || $httpCode == 204;
error_log('$httpCode: ' . $httpCode);
if (!$request_ok) {
$info = curl_error($curl);
$error_msg = $info ? $info : "Http code: " . $httpCode;
error_log('Error while checking url: ' . $url . ' : ' . $error_msg);
}
curl_close($curl);
return $error_msg;
}
but when I check it manually or even by curl from command line it works fine.
Probably I miss some configuration for curl here..
heh finally I found out that it is because one polish character.. :)
Related
I am working on some code on PHP that allow me to get json data from an api.
so
1 typical URL is not providing the data no matter what. when checking for empty in the $result, it says it has value in it, but when required to print it does not print or echo. This same URL when tested in PostMan works and provide data.
The strange part is the data are in the same format and
all other URLs calls work fine both on PostMan and through the code below.
I was able to trace to here and I am suspecting something is wrong with the "curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);" or the "curl_exec". the rest I am stuck!
All URL data return are similar and same format in PostMan.
No error returns.
function getRestCall($url, $data = null, $method = self::METHOD_GET)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
printf('<h2>URL</h2>' . $url);
// Set authentication parameters
curl_setopt($curl, CURLOPT_USERPWD, $this->username . ':' . $this->password);
// Don't send as json when attaching files to tasks.
if (is_string($data) || empty($data['file']))
{
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'content-Type: application/json'
)); // Send as JSON
}
// Dont print result
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set maximum timeout limit
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->timeout);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
// Don't verify SSL connection
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
// Define methods
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
if ($method == self::METHOD_POST)
{
curl_setopt($curl, CURLOPT_POST, true);
}
elseif ($method == self::METHOD_PUT)
{
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
}
elseif ($method == self::METHOD_DELETE)
{
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
// Define post data if we have the correct method
if (!is_null($data) && ($method == self::METHOD_POST || $method == self::METHOD_PUT))
{
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
try
{
$return = curl_exec($curl);
if ($this->debug)
{
$info = curl_getinfo($curl);
echo '<pre>';
print_r($info);
echo '</pre>';
if ($info['http_code'] == 0)
{
echo '<br />error num: ' . curl_errno($curl);
echo '<br />error: ' . curl_error($curl);
}
if (!is_null($data))
{
echo '<br />Sent info:<br /><pre>';
print_r($data);
echo '</pre>';
}
}
}
catch(Exception $e)
{
$return = null;
if ($this->debug)
{
echo "Exception caught: " . $e->getMessage();
}
}
if ($return === false)
{
printf('<h2>Return value is error, SHOW!!: </h2>');
$return = curl_error($curl);
//printf('<h2>Return value is not empty, SHOW!!: </h2>'. $return);
}else
{
printf('<h2>no error</h2>');
}
curl_close($curl);
return $return;
}
I am suspecting something is wrong with the "curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);" or the "curl_exec".
We are a little bit confuse how we can achieve this problem. We don't want to run the createsite function in our code if createSubaccount function fails. We would truly appreciate any feedbacks, comments, guides on our code.
<?php
//Set API user and password
define("API_USER","user");
define("API_PASS","pw");
$createdSite = createSite($_REQUEST['template_id'],$_REQUEST['original_url']);
//echo 'Site Created: ' . $createdSite . '<br/>';
$accountCreated = createSubAccount($_REQUEST['email']);//client email
//echo 'Account created: ' . $accountCreated . '<br/>';
$first_name = $_REQUEST['first_name'];//First Name
$last_name = $_REQUEST['last_name'];//Last Name
$retArr = ["sso"=>$sso_link,"ru"=>$resetURL,"ac"=>$accountCreated,"fn"=>$first_name,"ln"=>$last_name];//assoc array
print json_encode ($retArr);//json string
function createSite($template_id,$original_url) {
//create array with data
if($original_url) {
$data = array("template_id"=>$_REQUEST['template_id'],"url"=>$original_url);
} else {
$data = array("template_id"=>$_REQUEST['template_id']);
}
//turn data into json to pass via cURL
$data = json_encode($data);
//Set cURL parameters
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/api/create');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, API_USER.':'.API_PASS);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//execute cURL call and get template data
$output = curl_exec($ch);
//check for errors in cURL
if(curl_errno($ch)) {
die('Curl error: ' . curl_error($ch));
}
$output = json_decode($output);
return $output->site_name;//Output /Return : {"site_name":"28e1182c"}
}
function createSubAccount($emailToCreate) {
$first_name = $_REQUEST['first_name'];//First Name
$last_name = $_REQUEST['last_name'];//Last Name
$data = '{"account_name":"'.$emailToCreate.'", "first_name":"'.$first_name.'", "last_name":"'.$last_name.'"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/api/create');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, API_USER.':'.API_PASS);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//execute cURL call and get template data
$output = curl_exec($ch);
if(curl_getinfo($ch,CURLINFO_HTTP_CODE) == 204) {
curl_close($ch);
return $emailToCreate;//Expected return HTTP Code: 204 No Content
} else {
curl_close($ch);
$output = 'failed';
return $output;
die('Account creation failed, error: '. $output . '<br/>');
}
}
?>
This is where an Exception comes in handy.
function createSite() {
throw new \Exception('Failed');
}
try {
$createdSite = createSite($_REQUEST['template_id'],$_REQUEST['original_url']);
//echo 'Site Created: ' . $createdSite . '<br/>';
$accountCreated = createSubAccount($_REQUEST['email']);//client email
} catch(\Exception $err) {
echo $err->getMessage();
}
The Exception prevents the rest of the code in the block from executing once thrown.
Let's say I have a running service API that responds to a url like:
http://example.com/param/1
It's served on both get and post verbs.
Param=1 is the param considered
How should I perform correctly a curl request to pass the parameter (POST)?
If i browse: http://example.com/param/1
I'll have back the expected response (GET)
But if I do the following, it is not going to work:
$service_url = 'http://example.com/';
$curl = curl_init($service_url);
$curl_post_data = array('param'=>1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
Even changing it like the folowing won't work:
$service_url = 'http://example.com/param/1';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
This instead works: but i guess it still will be a GET
$service_url = 'http://example.com/param/1';
$curl = curl_init($service_url);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
$service_url = 'http://example.com/param/1';
$ch = curl_init($service_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "param1=value1¶m2=value2&..");
$response = curl_exec($ch);
curl_close($ch);
I have a sand box account in fortnox and i am trying to get the access token using following code, but i keep getting same error:
$requestMethod = "GET";
$ch = curl_init();
$options = array(
'Authorization-Code: '. AUTHORIZATION_CODE .'',
'Client-Secret: '. CLIENT_SECRET .'',
'Content-Type: '. CONTENT_TYPE .'',
'Accept: '. ACCEPTS .''
);
curl_setopt ($ch, CURLOPT_CAINFO, "/xampp/htdocs/cacert.pem");
curl_setopt($ch, CURLOPT_URL, "https://api.fortnox.se/3/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, $options);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestMethod);
$curlResponse = curl_exec($ch);
$info = curl_getinfo($ch);
//echo 'Took ' . $info['total_time'] . ' seconds for url ' . $info['url'];
echo $curlResponse;
if ($curlResponse === FALSE) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
Error: PHP / 4.5.37 Can not sign in , access tokens , or client- secret missing ( 2000311 ) .
I get the Access-Token using the following code which is very close to your code. It worked fine for me.
Your error is described on the Errors page, but it adds nothing new to the text you already shown.
Please note that you can retrive the Access-Token only once, check Authentication section in the Fortnox documentation.
An Access-Token can only be retrieved once with every Authorization-Code, multiple requests with the same Authorization-Code will make both the Authorization-Code and the Access-Token invalid.
public function actionRetrieveAccessToken($authCode, $clientSecret)
{
$headers = [
'Authorization-Code: ' . $authCode,
'Client-Secret: ' . $clientSecret,
'Content-Type: application/json',
'Accept: application/json',
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.fortnox.se/3/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$responseText = curl_exec($curl);
$response = json_decode($responseText, true);
if (isset($response['ErrorInformation'])) {
echo 'Request failed with error messages:' . PHP_EOL;
echo $response['ErrorInformation']['Error'] . ': ';
echo $response['ErrorInformation']['Message'];
echo ' (' . $response['ErrorInformation']['Code'] . ')' . PHP_EOL;
} else {
echo 'Access Token: ' . $response['Authorization']['AccessToken'] . PHP_EOL;
}
}
$content_type = 'application/json';
$api_url="api url here";
$curl = curl_init();
$headers = array(
'Content-Type: '.$content_type.'',
'Authorization : '.'Bearer ' . $this->access_token
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($data))
{
$data = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($curl);
logthis($response,"utils");
curl_close($curl);
I'm trying to pull information from Evergage, but based on my console log debugging, the function terminates at the curl_exec function (see comment). debug_to_console("success"); and curl_error both return nothing at all. However, if I debug_to_console("success"); just before curl_exec, it returns properly. When I test run the function, it runs for about 30 seconds and then ends. I originally thought it was a timeout, so I tried removing any time restrictions but it still doesn't seem to be working. Any help would be greatly appreciated. Thanks!
function RetrieveData($account, $dataset, $kind, $apiToken)
{
$port = "";
if ($account === "localtest") {
$port = ":8443";
}
$requestURI = "https://" . $account . ".evergage.com" . $port . "/api/dataset/" . $dataset . "/" . $kind . ".json?_at=" . $apiToken;
debug_to_console("request URL: " . $requestURI);
$session = curl_init();
curl_setopt($session, CURLOPT_FAILONERROR, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($session, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($session, CURLOPT_URL, $requestURI);
// EVERYTHING RUNS FINE UP TO THIS POINT
set_time_limit(0);
$response = curl_exec($session);
debug_to_console("success");
echo 'Curl error: ' . curl_error($session);
$info = curl_getinfo($session);
$responseCode = $info["http_code"];
if ($responseCode >= 300) {
print("Error loading data: " . $responseCode . "<br/>");
print($response);
} else {
$body = substr($response, $info['header_size']);
$decoded_result = json_decode($body, true);
}
curl_close($session);
return $decoded_result;
}
Edit: I should mention that I have printed out $requestURI and it is correct. Navigating to it results in the JSON information that I need downloading right away.