What does curl_exec return?
Asked Answered
M

1

24

I'm trying to set an API with a payment processor. Below is the code they provided me. There are some information in the $result variable that I want, what I don't understand is what type of variable is '$result' and how can I take certain data from it. printing the $result shows "Transaction ID is : xxxx status is ACCEPTED". What I basicly want is to take only the transaction ID and store it in a variable.

foreach($_POST as $k=>$v) $$k=urldecode($v); 
$urladdress = "https://example.com/accapi/process.php"; 
$api_id = "dddd"; 
$api_pwd = "yyyyy"; 
$api_pwd = md5($api_pwd.'s+E_a*'); 
$data = "user=".$user. "&testmode=".$testmode."&api_id=".$api_id. "&api_pwd=".$api_pwd."&amount=".$amount."&paycurrency=".$currency."&comments=".$comments."&fee=".$fee."&udf1=".$udf1;
// Call STP API

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"$urladdress"); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 0); //use this to suppress output 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);// tell cURL to graciously accept an SSL certificate 
$result = curl_exec ($ch) or die(curl_error($ch)); 
echo $result; 
echo curl_error($ch); 
curl_close ($ch);
Mackenie answered 9/5, 2013 at 0:55 Comment(0)
R
65

From the manual:

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

Your code already contains this line (which is good):

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

The 1 means you will receive an explanatory result back from $result = curl_exec ($ch) instead of just true or false.

Your error checking code could therefore look like:

$result = curl_exec ($ch);
if($result === FALSE) {
    die(curl_error($ch));
}

You can also check the type of variable returned via var_dump: var_dump($result).


PS: hanshenrik shared an alternative to the above error handling, using a RuntimeException instead of using die(). I recommend to use this instead but leaving the old answer above unchanged.

curl_exec ($ch);
if(curl_errno($ch) !== CURLE_OK){
    throw new RuntimeException(curl_error($ch));
}
Realm answered 9/5, 2013 at 0:57 Comment(3)
Oh, I see so it returns a string on success. Thank you very much!, so all I have to do is use string functions to seperate the transaction ID?Mackenie
"From PHP 5.1.3, this option has no effect: the raw output will always be returned when CURLOPT_RETURNTRANSFER is used".Longdrawn
if(curl_errno($ch) !== CURLE_OK){throw new RuntimeException(curl_error($ch));}Droopy

© 2022 - 2024 — McMap. All rights reserved.