user1801060
user1801060

Reputation: 2821

var_dump of a JSON response returns NULL

I'm writing a script to accept Bitcoin payments. My $json variable returns null. var_dump() returns NULL.

Things I've tried: 1. I've taken the value of $callbackurl and $recievingaddress pasted a URL directly into my browser and I have gotten a JSON response

  1. I've used json_last_error and recieved a 'no error' response

  2. I've escaped magic_quotes but this has no effect

What am I doing wrong?

    $receiving_address = BITCOIN_ADDRESS;
    if(get_magic_quotes_gpc()){
        $callback_url = urlencode(stripslashes(CALLBACK_URL));
    }  else {
        $callback_url = urlencode(CALLBACK_URL);
    }

    $ch = curl_init("https://blockchain.info/api/receive?method=create&address=$receiving_address&shared=false&callback=$callback_url");
    curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $json=json_decode(curl_exec($ch),true);

    var_dump($json);
    echo $json[0]->text;

Corrected code is as follows:

    $receiving_address = BITCOIN_ADDRESS;
    if (get_magic_quotes_gpc()) {
        $callback_url = urlencode(stripslashes(CALLBACK_URL));
    } else {
        $callback_url = urlencode(CALLBACK_URL);
    }

    $ch = curl_init("https://blockchain.info/api/receive?method=create&address=$receiving_address&shared=false&callback=$callback_url");
    curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CAINFO, "C:\Program Files\BitNami WAMPStack\apache2\htdocs\coming\cacert.pem");

    $res = curl_exec($ch);
    if ($res === FALSE) {
        die("Curl failed with error: " . curl_error($ch));
    }


    //var_dump($res);
    $json = json_decode($res, true);

Upvotes: 1

Views: 2371

Answers (1)

Marc B
Marc B

Reputation: 360762

Do NOT chain your curl/json calls like that. You're simply assuming we live in a perfect world and nothing could ever fail. That is a very bad decision. Always assume that external resources can and will fail, and check for failure at each stage. Change your code to:

$response = curl_exec($ch);
if ($result === FALSE) {
   die("Curl failed with error: " . curl_error($ch));
}
$json = json_decode($response, true);
if (is_null($json)) {
   die("Json decoding failed with error: ". json_last_error());
}

Upvotes: 2

Related Questions