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)
Related
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?
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'];
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.
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;
}
I am currently writing an C# windows service, which integrates with a PHP page. I have an example of code making the request in PHP which is below however I have never developed in PHP and don't understand how the cURL function performs the request.
Is there anyway to retrieve the request which is being sent? Or can anyone provide an example of how the request would look and how the request is sent so I can replicate the request in C#.
Thank you for any help.
public function api(/* polymorphic */) {
$args = func_get_args();
if (is_array($args[0])) {
$serviceId = $this->getApiServiceId($args[0]["method"]);
unset($args[0]["method"]);
$args[0]["serviceId"] = $serviceId;
$args[0]["dealerId"] = $this->dealerId;
$args[0]["username"] = $this->username;
$args[0]["password"] = $this->password;
$args[0]["baseDomain"] = $this->baseDomain;
return json_decode($this->makeRequest($args[0]));
} else {
throw Exception("API call failed. Improper call.");
}
}
protected function makeRequest($params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->useFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
$e = new WPSApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
Add the option CURLINFO_HEADER_OUT to curl handle, then call curl_getinfo on it after execing.
As in:
//...
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
//...
curl_exec($ch);
//...
$header = curl_getinfo(CURLINFO_HEADER_OUT);
echo $header;