3

I"m setting up a mock for a service and trying to return some data to my callback page to save to a db table.

This is the code that I'm using to send the mock to the callback:

function checkCallback(){

            $ch = curl_init("remote.domain.com/callback.php");

$jsonData = [


    "success" =>true,      
    "error" => null, 
"response"=> [
        "code"=>"ad3f0db2-62b6-4cf4-9027-14829d33cfd2",
        "state"=>"my-secret-state-123456789"
    ]

            ];

            $jsonDataEncoded = json_encode($jsonData);

            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);


            $result = curl_exec($ch);


            var_dump($result);
            echo $jsonDataEncoded;
              curl_close($ch);

}

callback.php:

<?php 


var_dump(get_defined_vars());

$un = 'username';
$pw = 'password';
$dsn = "mysql:host=localhost;port=3306;dbname=safelocal;charset=utf8";
$pdo_options = array(PDO::ATTR_EMULATE_PREPARES => false, 
                     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);


$db = new PDO($dsn, $un, $pw, $pdo_options);



    $updateUserData = $db->prepare('INSERT into `table` (`message`, `extra`) VALUES(:msg, :extra)');
            $updateUserData->execute([
                ':msg' =>$_POST["response"],
                ':extra' => $_POST["code"]
                                ]);

All I get back is a this strange response:

myfile.php:77:string 'array(4) {
  ["_GET"]=>
  array(0) {
  }
  ["_POST"]=>
  array(1) {
    ["{"success":true,"error":null,"response":{"code":"ad3f0db2-62b6-4cf4-9027-14829d33cfd2","state":"my-secret-state-123456789"}}"]=>
    string(0) ""
  }
  ["_COOKIE"]=>
  array(0) {
  }
  ["_FILES"]=>
  array(0) {
  }
}
' (length=291)

so we can see my data here, but how do we get it to act as key,value pairs so I can manipulate the data? Any guidance is appreciated.

4
  • it looks like the response you get back is from the var_dump and nothing from any db calls ~ try and see what you get when you do print_r( $_POST ) in the callback.php script Commented Sep 11, 2016 at 8:44
  • same, loads it with the entire data structure into the key rather than into each key and value pair Commented Sep 11, 2016 at 8:47
  • Why do you pass your data as json encoded? Commented Sep 11, 2016 at 8:54
  • I strongly recommend using a Http client like Guzzle to make http requests and handle the responses. Using plain curl_ functions to fetch/send data from/to a resource produces more headaches and bugs than you think. Commented Sep 11, 2016 at 8:56

3 Answers 3

2

I'm not sure why you pass your data as json_string, but obviously a json string is considered a url_encoded string and decodes in what you get in your variables.

If json is not a requirement - you can pass your array directly to curl_setopt or encode it with http_build_query:

// passing raw array:
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

// passing query string:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonData));
Sign up to request clarification or add additional context in comments.

1 Comment

I don't know if this is the right fix for all circumstances, but this at least let me simulate what I needed and is a step in the right direction for me. Passing my array directly in http_build_query did it, setopt wasn't good for the embedded array
0

I'm not sure this is what you were trying to do or whether it will work as it's not tested. There were a couple of issues - the Content-Type header had suprious extra single quotes, the url for the curl request didn't have the protocol ( though that might not be an issue ), the callback was echhoing out the input data rather than any response from remote script and as the data was json_encoded prior to sending it makes sense that it should be decoded before accessing at the remote script. Hope it helps.

function checkCallback(){
    $ch = curl_init("http://remote.domain.com/callback.php");

    $jsonData = array(
        "success" =>true,      
        "error" => null, 
        "response"=> array(
            "code"=>"ad3f0db2-62b6-4cf4-9027-14829d33cfd2",
            "state"=>"my-secret-state-123456789"
        )
    );

    $jsonDataEncoded = json_encode( $jsonData );

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" ) ); 


    $result = curl_exec($ch);
    curl_close($ch);

    echo $result;
}


<?php

    $un = 'username';
    $pw = 'password';

    $dsn = "mysql:host=localhost;port=3306;dbname=safelocal;charset=utf8";
    $pdo_options = array(
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    );

    $data=json_decode( $_POST );
    $msg=$data['response'];
    $extra=$data['code'];



    $db = new PDO( $dsn, $un, $pw, $pdo_options );

    $updateUserData = $db->prepare('INSERT into `table` (`message`, `extra`) VALUES (:msg, :extra)');
    $updateUserData->execute( array(
        ':msg'      =>  $msg,
        ':extra'    =>  $extra
    ));

    /* send any response data */
    print_r( $data );

?>

Comments

0

You need to set CURLOPT_HTTPHEADER option for the curl:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

then in the script where you receive the data you should use:

$data = json_decode(file_get_contents('php://input'), true);

this way in the $data variable you will have associative array with the values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.