Handling errors in a PHP class - php

I try to handle errors in a class written in PHP and using curl, this class uses 3 functions (init, sendFirstForm, sendSecondForm) dependent on one another, I test result via nested statements.
I want to manage two types of errors (Curl connection errors and form errors) that requires the sending of an email so I can fix them.
This code does not work.
class Sender {
public $error;
public function __construct() {
$this->error = '';
}
public function send() {
if($this->init() === TRUE) /* account login and retrieval of the cookie */
{
if($this->sendFirstForm() === TRUE) /* sending the first form if connection */
{
if($this->sendSecondForm() === TRUE) /* sending the second form if connection */
{
echo 'Annonce publiée avec succès.';
}
}
}
}
public function init() {
// CuRL : account login and retrieval of the cookie
// ...
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($ch);
if(curl_errno($ch))
{
$this->error = 'CuRL Error : ' . curl_error($ch);
return $this->error;
}
elseif(preg_match("/\bError\b/i", $result)) /* $ _POST data missing and / or incorrect */
{
$this->error = 'Error in the login form';
return $this->error;
mail('name#domain.com', 'Error Curl', 'Error connecting to the account, here are the data sent : ' . $postfields);
}
}
public function sendFirstForm() {
// CuRL : sending the first form
// ...
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($ch);
if(curl_errno($ch))
{
$this->error = 'CuRL Error : ' . curl_error($ch);
return $this->error;
}
elseif(preg_match("/\bError\b/i", $result)) /* $ _POST data missing and / or incorrect */
{
$this->error = 'Error in the first form';
return $this->error;
mail('name#domain.com', 'Error Curl', 'Error sending first form, here are the data sent : ' . $postfields);
}
}
public function sendSecondForm() {
// CuRL : sending the second form
// ...
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($ch);
if(curl_errno($ch))
{
$this->error = 'CuRL Error : ' . curl_error($ch);
return $this->error;
}
elseif(preg_match("/\bError\b/i", $result)) /* $ _POST data missing and / or incorrect */
{
$this->error = 'Error in the second form';
return $this->error;
mail('name#domain.com', 'Error Curl', 'Error sending second form, here are the data sent : ' . $postfields);
}
}
}
$send = new Sender();
$send->Send();
if(empty($send->error))
{
// MySQL treatment
}
else
{
echo $send->error;
}

Related

get facebook page contents from access token

I am trying to get facebook page contents using graph api in codeigniter. when I use access token in controller with a get function, I get the contents. But when I try to use graph url in view file, It's showing an error -- " Invalid OAuth access token"
In my controller, I tried this--
$response2 = $this->get('/me?fields=id,name,posts{actions,comments,message}',$accessToken);
echo "<pre>";
print_r($response2);
the get function is--
public function get($params, $accessToken){
try {
$response = $this->fb->get($params, $accessToken);
return json_decode($response->getBody());
} catch(Facebook\Exceptions\FacebookResponseException $e) {
return $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
return $e->getMessage();
}
}
Here I got the result .
but If I try to use it another view file--
<?php
foreach ($h->result() as $row) {
if ($row->social_network == 'facebook') {
$token = $row->token;
$id = $row->pid;
print_r($id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v15.0/$id?fields=posts%7Bmessage%2Ccomments%2Cactions%7D&access_token=$token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
$result = json_decode($result);
print_r($result);
}
}
?>
Here I am getting the access token from database that I previously stored. Here It shows me an error--
Invalid OAuth access token - Cannot parse access token
How do I make It work?

integrating seat seller api using codeigniter .Error: ExceptionRequest failed with code 401: Error: OAUTH verification failed

I have successfully done oauth1.0 authentication for the get methods provided in the api document
http://api.seatseller.travel/docs/interface.html
But I am getting issue in blockticket url in the above document URL : http://api.seatseller.travel/blockTicket. I need to post the parameters along .I have used Oauth1.0 2Leg library in codeigniter.But its giving me the error as :
ExceptionRequest failed with code 401: Error: OAUTH verification
failed.
Take reference of this url for Oauth library. https://github.com/jesstelford/OAuth-PHP
In codeigniter/application/helpers I have created a helper in that I coded
include_once APPPATH . 'libraries/OAuth/OAuthStore.php';
include_once APPPATH . 'libraries/OAuth/OAuthRequester.php';
function getbusUrlPost($url,$data) {
$key = 'key';
$secret = 'secret';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "POST";
$params =$data;
//var_dump($params);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method,$params);
$result = $request->doRequest(0);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int,
'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response !=
'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo $response;
}
else
{
ECHO '------';
}
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
}
in controller:
<?php
include_once APPPATH . 'libraries/REST_Controller.php';
class BusBooking extends Rest_Controller {
public function get_bus_blockTicket_post() {
if(isset($_REQUEST['availableTripID']) &&
isset($_REQUEST['seatname'])
&& isset($_REQUEST['fare']) &&
isset($_REQUEST['ladiesSeat'])
&& isset($_REQUEST['name']) && isset($_REQUEST['mobile'])
&& isset($_REQUEST['title'])
&& isset($_REQUEST['email']) && isset($_REQUEST['age']) &&
isset($_REQUEST['gender'])){
$url="http://api.seatseller.travel/blockTicket";
$data=array(
'availableTripID'=>$_REQUEST['availableTripID'],
'seatname'=>$_REQUEST['seatname'],
'fare'=>$_REQUEST['fare'],
'ladiesSeat'=>$_REQUEST['ladiesSeat'],
'name'=>$_REQUEST['name'],
'mobile'=>$_REQUEST['mobile'],
'title'=>$_REQUEST['title'],
'email'=>$_REQUEST['email'],
'age'=>$_REQUEST['age'],
'gender'=>$_REQUEST['gender']
);
$sources= getbusUrlPost($url, $data);
}
}
I have also tried with curl. But getting same error.Check the following code with curl.
function getBusblock($data) {
$url="http://api.seatseller.travel/blockTicket";
$header[]= 'Content-Type: application/x-www-form-urlencoded';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('oauth_consumer_key'=>"key",'oauth_signature_method'=>"HMAC-
SHA1",'oauth_timestamp'=>'1557752217','oauth_nonce'=>'5cd969995be23','oauth_version'=>'1.0','oauth_signature'=>'DsMdvOOUI57VTkx5VQokUmi9rvw%3D&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}
echo "<pre>";
echo json_encode($result);
echo "</pre>";
exit;
}
Please help me.I have tried much but I am getting Oauth verification failed issue.
I am expecting response in json format with all the ticket details .But getting this output :
ExceptionRequest failed with code 401: Error: OAUTH verification failed.
when hitted webservice with postman.
Use
CURLOPT_HTTPHEADER
instead of
CURLOPT_POSTFIELDS

PHP Function - Trapping for Error or Success Result

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.

Code that works fine on local but not on server

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)

How to override the Exception Class and not to display the Fatal error

I am trying to write a class that communicate with an API. I would like to override the standard Exception class in PHP to return the message, error code that I want.
I have added this extension
<?php namespace API;
/**
* API Exception
*
* #package ICWS
*/
class ApiException extends \Exception
{
public function __construct($message, $code = 0)
{
// Custom ICWS API Exception Message
$apiMessage = 'ICWS API Error: ' . $message;
//More code to come to custom the error message/code.....
// Run parent construct using custom message
parent::__construct($apiMessage, $code);
}
}
?>
Then when needed I create new ApiException like so
throw new ApiException($errorMessage, $errorNo);
Finally I wrap the function that throws an exception by try{} catch() block to capture the exception.
However, I still get the a fatal error instead of just the message that I provided.
Here is my code
public function createSession($userID, $password){
$data = array('userID' => $userID,
'password' => $password);
try {
$data = $this->_makeCall('POST', 'connection', $data);
$this->_csrfToken = $data['csrfToken'];
$this->_sessionId = $data['sessionId'];
$this->_alternateHostList = $data['alternateHostList'];
} catch (Exception $e){
$this->_displayError($e);
}
}
private function _makeCall($uri, $data = false, $header = array())
{
$ch = curl_init();
$url = $this->_baseURL . $uri;
//disable the use of cached connection
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_URL, $url);
//return the respond from the API
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_POST, true);
if ($data){
$JSON = json_encode( $data );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $JSON );
}
$result = curl_exec($ch);
//throw cURL exception
if($result === false){
$errorNo = curl_errno($ch);
$errorMessage = curl_error($ch);
throw new ApiException($errorMessage, $errorNo);
}
$result = json_decode($result, true);
//throw API exception
if( $this->_hasAPIError($result) )
){
throw new ApiException($result['message'], 0);
}
return $result;
}
private function _displayError(Exception $e){
echo 'Error Number: ' . $e->getCode() . "\n";
echo 'Error Description: ' . $e->getMessage() . "\n\n";
}
private function _hasAPIError($result){
if( isset($result['errorId']) && !empty($result['errorId'])
&& isset($result['errorCode']) && !empty($result['errorCode'])
&& isset($result['message']) && !empty($result['message'])
){
return true;
}
return false;
}
I would like to see something like this at then end "if there is an error"
Error Number: 0
Error Description: ICWS API Error: The authentication process failed
This is what I currently get
Fatal error: Uncaught exception 'API\ApiException' with message 'ICWS API Error: The authentication process failed.' in C:\phpsites\icws\API\ICWS.php:130 Stack trace: #0 C:\phpsites\icws\API\ICWS.php(57): API\ICWS->_makeCall('connection', Array) #1 C:\phpsites\icws\index.php(17): API\ICWS->createSession('user', 'pass') #2 {main} thrown in C:\phpsites\icws\API\ICWS.php on line 130
You did not import the Exception class into your namespace, so when doing catch (Exception $e), Exception is an unknown class (because PHP is assuming API\Exception) and PHP will not notice that APIException is a subclass of Exception. Curiously, PHP does not complain about catching a non-existing class (I've just confirmed this locally with PHP 5.6.8).
The following should work:
catch (\Exception $e) {
// ...
}
Alternatively:
use Exception;
// ...
catch (\Exception $e) {
// ...
}
The error is that you are catching Exception, not ApiException. Try this:
try {
$data = $this->_makeCall('POST', 'connection', $data);
$this->_csrfToken = $data['csrfToken'];
$this->_sessionId = $data['sessionId'];
$this->_alternateHostList = $data['alternateHostList'];
} catch (ApiException $e){ // Here is the change: Exception to ApiException
$this->_displayError($e);
}

Categories