I would like to return a user friendly "Client Does Not Exist" instead of Notice: Undefined Index error.
I have an IF statement to capture errors however it seems like PHP CURL does not see this as an error it is more a statement.
I am using a $_GET to get a variable from my URL:
$Url = $_GET['hotel'];
The error catchment i am using is:
$response = curl_exec($curl);
$err = curl_error($curl);
$responseDataFetch = json_decode($response, true);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $responseDataFetch['name'];
}
I am not always going to have a correct hotel variable in my URL as this is more a lookup function.
I want to change the return from Notice: Undefined Index to "This user does not exist"
Just use an isset() check:
$response = curl_exec($curl);
$err = curl_error($curl);
$responseDataFetch = json_decode($response, true);
curl_close($curl);
if ( $err ) {
//echo cURL error
echo "cURL Error #:" . $err;
die();
}
if (! isset( $responseDataFetch['name'] ) ) {
//echo error if not found
echo "This user does not exist";
die();
}
//echo response if found
echo $responseDataFetch['name'];
Related
I am using cURL and PHP to make a request to a test API to return a list of users but I get the following error:
PHP Notice: Trying to get property 'id' of non-object
Not sure where I am going wrong.
Here is my code
<?php
// I am using the JSONPlaceholder website as a test API
$url = 'https://jsonplaceholder.typicode.com/users';
// Initial a new cURL session
$request = curl_init($url);
// Return request as string
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
// Run cURL / execute http request
$response = curl_exec($request);
// Close the cURL resource
curl_close($request);
if ($response === false) {
print "Could not make successful request\n";
} else {
$response = json_decode($response);
print $response->id . "\n";
print $response->name . "\n";
print $response->username . "\n";
}
?>
you have to loop through the response:
if ($response === false) {
print "Could not make successful request\n";
} else {
$response = json_decode($response);
foreach ($response as $item) {
print $item->id . "\n";
print $item->name . "\n";
print $item->username . "\n";
}
}
I have the following request to an API:
$url = "{{correctURLishere}}";
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
The This should bring back the value from they key "title" in this json response. But instead, the error I get is
file_get_contents(url): failed to open stream: HTTP request failed!
HTTP/1.1 402
I know the error is because I am only allowed 150 requests a day and have exceeded this amount but can someone help me to echo "No more requests allowed" instead of the error?
I have tried the following but it wont work:
if(json_decode(file_get_contents($url), true)) {
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
Could anyone tell me how to help with the error? Thanks
try to use try catch section, for example
try{
if(json_decode(file_get_contents($url), true)) {
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
}catch(Exception $e){
print_r($e);
echo '<br>';
echo $e->getMessage();
}
for your referrence: https://www.php.net/manual/en/language.exceptions.php
I'm working on my first function with PHP - it's a login function that calls cURL to login to an API. This is all working well so far, but I would like to add some error checking so that if the login fails or succeeds I can branch for that.
There's 2 possible types of errors that I can see:
cURL errors
API login errors
If there are no cURL errors the API will return a response in JSON like this for a successful login:
{
"token": "6a2b4af445bb7e02a77891a380f7a47a57d3f99ff408ec57a62a",
"layout": "Tasks",
"errorCode": "0",
"result": "OK"
}
and this for a failed login:
{
"errorMessage": "Invalid user account and/or password; please try again",
"errorCode": "212"
}
so that should be easy enough to trap for by the error code or result value. If there is a cURL error there could be many types of errors.
Here's the outline of my function at the moment:
function Login ($username, $password, $layout) {
$curl = curl_init();
// set curl options
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
return json_decode($response, true);
}
}
and I call it via:
$login = Login($username, $password, $layout);
Looking for advice on how I can return an error if there was a curl error and check the response on the calling page that calls the function.
As suggested by #larwence-cherone in the comments, you should throw and catch exceptions.
// note: made the method name lowercase, because uppercase usually indicates a class
function login ($username, $password, $layout) {
$curl = curl_init();
// set curl options
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
throw new Exception($err);
} else {
// returns an associative array
$result = json_decode($response, true);
// the status was not OK or if we received an error code.
// Check the API doc for a recommended way to do this
if ($result['result'] !== 'OK' || $result['errorCode'] > 0) {
$errorMessage = $result['errorMessage'];
// no error message: return a genuine error
if (!$errorMessage) {
$errorMessage = 'An undefined error occurred';
}
throw new Exception($errorMessage);
}
// if no error occurred, return the API result as an
return $result;
}
}
call the method in a try/catch block:
try {
$login = login($username, $password, $layout);
print_r($login);
} catch (Exception $error) {
echo $error;
}
If you want to refine it, you could create your own exception(s) by extending the SPL Exception class.
So the purpose of my code is to get response from curl.
Here is a reference method
public function waybill($waybill, $courier)
{
$curl = curl_init();
curl_setopt_array($curl, array(
[Some CURLOPT here..]
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return "cURL Error #:" . $err;
} else {
return $response;
}
}
And from here i call the method
public function getWaybill($carrier, $tracking_number)
{
$waybill = $tracking_number;
$courier = strtolower($carrier);
$response = $this->helper->waybill($waybill, $courier);
$response = json_decode($response, true);
$response = $response['rajaongkir']['result'];
$response = $response['summary']['status'];
if (!empty($response)) {
return $response;
} else {
return "Invalid tracking data";
}
}
In local appear "Invalid tracking data" if response is empty, however in server does not appear anything.
Try creating another page with just this on it
<?php
if (in_array ('curl', get_loaded_extensions())) {
echo true;
}
else {
echo false;
}
This will let you know if curl is enabled (if get_loaded_extensions() isn't disabled) ... Might be your issue..
Otherwise the old
<?php phpinfo();
and search for curl would work too (if phpinfo is allowed on your server)
I am currently using the reCaptcha library available here to run reCaptcha on my web site which uses LAMP version 2.2.22, and PHP version 5.4.39-0+deb7u2, on Debian 6.5. My PHP code is as follows.
// Recaptcha check
$secret = "SomeAlphaNumericGibberish";
$response = null;
$reCaptcha = new ReCaptcha($secret);
if ($reCaptcha ==NULL){
echo "Null pointer " . "<br>";
} else{
echo "Valid pointer " . "<br>";
}
if ($_POST["g-recaptcha-response"]) {
echo "Remote IP: ". $_SERVER["REMOTE_ADDR"] . "<br>";
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
echo "Welcome " . $_POST["username"] . "!" . "<br>";
} else if ($response == null) {echo "Null pointer " . "<br>";}
else {
echo "Bad response" . "<br>";
foreach ($response->getErrorCodes() as $code) {
echo $code . "<br>";
}
echo "End of error codes" . "<br>";
}
The output is as follows
Valid pointer
Remote IP: 192.168.1.4
Bad response
However, I don't get any output after that. I ran
sudo cat /var/log/apache2/error.log
and got
PHP Fatal error: Call to undefined method ReCaptchaResponse::getErrorCodes()
I was unable to find any discussions about this error message.
No need to even use that library at all. it adds unnecessary weight.
Assuming you are using the latest recaptcha js library and your html is configured, this will work:
$recaptchasecret = 'adslfjasdlf';
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify?secret='.
$recaptchasecret.'&response='.$_POST['g-recaptcha-response'].'&remoteip='.$_SERVER['REMOTE_ADDR'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $recaptcha_url,
CURLOPT_USERAGENT => 'MyWebsite.Com'
));
$response = curl_exec($curl);
curl_close($curl);
unset($curl);
$auth = json_decode($response,false);
if(!$auth->success){
throw new exception('Captcha Failed!');
}