php Curl vs postman giving different results on error - php

I have a php curl script that returns the results of a get the run as a command from another process. The code is:
<?php
$arr = getopt("f:");
$url = $arr['f'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
} else {
echo $result;
}
curl_close($ch);
?>
When I do a api get request for a specific url with curl that gives a 400 error, curl_error($ch) is "The requested URL returned error: 400 Bad Request"
When I run the same request in postman, I get a json reply such as: {"result_ok":false,"code":400,"message":"Invalid Email: xxxxxxxxxx#ail.com (POST)"}.
How can I get the json returned in the curl request? If I echo the $result when there is an error condition, it is null.

From CURLOPT_FAILONERROR explained:
fail the request if the HTTP code returned is equal to or larger than 400. The default action would be to return the page normally, ignoring that code.
CURLOPT_FAILONERROR is false by default so either remove it or set it:
curl_setopt($ch, CURLOPT_FAILONERROR, false);

Related

Udemy Affiliate API - Authentication Error (403 Notice Array to string conversion)

I'm trying to use the Udemy API with the correct answer from this Stackoverflow's post: curl request in udemy api is not working
header('Content-Type: application/json');
$url = "https://www.udemy.com/api-2.0/courses";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id: xxx','X-Udemy-Client-Secret: xxx',"Authorization: base64 encoded value of client-id:client-secret","Accept: application/json, text/plain, */*"));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$result=curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
echo curl_getinfo($ch,CURLINFO_HTTP_CODE);
// Closing
curl_close($ch);
// Will dump a beauty json :3
echo $result = json_decode($result,true);
I have added my own client ID and secret ID and tested them on the Udemy sites getting a status 200.
The error I get from the code above is: 403 Notice Array to string conversion.
Can anyone sees what am I missing?
echo $result = json_decode($result,true);
json_decode() turns the response (string containing a JSON) into an associative array.
You then pass the array to echo and this raises the error.
The fix:
echo $result; // `$result` is still a string (the response)
Then if you need to access the response as an associative array
$result = json_decode($result,true);

PHP: How to GET request a page and get body and http error codes

I want know if is possible to get the HTTP error codes and response in case of error instead of false (file get contents error) and error throwed. I'm using file_get_contents on PHP 7.2
I already tried doing this:
$r = file_get_contents("https://somewebsite");
Output:
PHP Warning: file_get_contents(https://somewebsite): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
I can get the response code with $http_response_header but $r is false and i want get the error response page.
You should try with curl
$ch = curl_init('https://httpstat.us/404');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// if you want to follow redirections
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// you may want to disable certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 400) {
// error
// but $response still contain the response
} else {
// everything is fine
}
curl_close($ch);
Using file get contents
$context = stream_context_create(array(
'http' => array('ignore_errors' => true),
));
$result = file_get_contents('http://your/url', false, $context);

PHP & CURL scraping

I have a problem when I run this script in Google Chrome I got a blank page. When I use another link of a web site, it works successfully. I do not what is happening.
$curl = curl_init();
$url = "https://www.danmurphys.com.au/dm/home";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
echo $output;
There are some conditions which make your result blank. Such as:
Curl error.
Redirection without response body and the curl doesn't follow the redirection.
The target host doesn't give any response body.
So here you have to find out the problem.
For the first possibility, use curl_error and curl_errno to confirm that the curl wasn't errored when its runtime.
For the second, use CURLOPT_FOLLOWLOCATION option to make sure the curl follows the redirection.
For the third possibility, we can use curl_getinfo. It returns an array which contains "size_download". The size_download shows you the length of the response body. If it is zero that is why you see a blank page when printing it.
One more, try to use var_dump to see the output (debug purpose only). There is a possibility where the curl_exec returns bool false or null. If you print the bool false or null it will show a blank.
Here is the example to use all of them.
<?php
$curl = curl_init();
$url = "https://www.danmurphys.com.au/dm/home";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
$ern = curl_errno($curl);
if ($ern) {
printf("An error occurred: (%d) %s\n", $ern, $err);
exit(1);
}
curl_close($curl);
printf("Response body size: %d\n", $info["size_download"]);
// Debug only.
// var_dump($output);
echo $output;
Hope this can help you.
Update:
You can use CURLOPT_VERBOSE to see the request and response information in details.
Just add this
curl_setopt($curl, CURLOPT_VERBOSE, true);
It doesn't need to be printed, the curl will print it for you during runtime.

Can't get JSON data from Google Maps request with cuRL

I'm trying to write a request with curl. I want to get the distance between two points. Therefore I'm getting the data of those points from my db to build the string. The final string looks like this when I echo it.
http://maps.googleapis.com/maps/api/distancematrix/json?origins=40215+Düsseldorf+Königsallee 59&destinations=40215+Düsseldorf&sensor=false
I also tried it with https instead of http but the result was the same.
As you can see, it returns a perfectly fine JSON-Response, but when I do this afterwards, I always get an error.
public function request($signedUrl) {
$ch = curl_init($signedUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$this->response = json_decode($data);
}
The $signedUrl is the requestUrl.
The error from Google I get, when I var_dump($data) is
400. That’s an error.
Your client has issued a malformed or illegal request. That’s all we know. "
When I var_dump the response, it just gives me null.
What could be the problem here and how could I fix it? I also tried to read it in with file_get_contents but without success
Works [Tested] . You got a bad request since the URL was not encoded.
<?php
$urlx='http://maps.googleapis.com/maps/api/distancematrix/json?origins=40215+D%C3%BCsseldor%20%E2%80%8Bf+K%C3%B6nigsallee59&destinations=40215+D%C3%BCsseldorf&sensor=false';
$ch = curl_init($urlx);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
var_dump(($data));

cURL operation and PHP

I have a frontend code
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
//make the request
$responseJSON = curl_exec($ch);
$response_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_status == 200) { // success
// remove any "problematic" characters from the json string and then decode
if (debug) {
echo "----finish API of getAPI inside basic_function with status==200---";
echo "<br>";
echo "-------the json response is-------" ; //.$responseJSON;
var_dump($responseJSON);
//print_r($responseJSON);
echo "<br>";
}
return json_decode( preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $responseJSON ) );
}
and I have a backend code which executed when cURL fired its operation with its URL. The backend code would therefore activated. So, I know cURL is operating.
$output=array (
'status'=>'OK',
'data'=>'12345'
)
$output=json_encode($output)
echo $output;
and $output shown on browser as {"status":"OK","data":"12345"}
However, I gone back to the frontend code and did echo $responseJSON, I got nothing. I thought the output of {"status":"OK","data":"12345"} would gone to the $responseJSON. any idea?
Here's output on Browser, something is very odd! the response_status got 200 which is success even before the parsing of API by the backend code. I expect status =200 and json response after the {"status":"OK","data":"12345"}
=========================================================================================
inside the get API of the basic functions
-------url of cURL is -----http://localhost/test/api/session/login/?device_duid=website&UserName=joe&Password=1234&Submit=Submit
----finish API of getAPI inside basic_function with status==200---
-------the json response is-------string(1153)
"************inside Backend API.php******************
---command of api is--/session/login/
---first element of api is--UserName=joe
--second element of api is---Password=1234
---third element of api is----Submit=Submit
----fourth element of api is---
-------inside session login of api-------------
{"status":"OK","data":"12345"}
Have you tried with curl_setopt($ch, CURLOPT_TIMEOUT, 10); commented?
See what happends if you comment that line.
Also try with the a basic code, if that works, smthing you added later is wrong:
// 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, false);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Try var_dump($responseJSON)
If it returns false try
curl_error ( $ch )
Returns a clear text error message for the last cURL operation.
Are you sure your $url is correct?

Categories