Frankenmint
Frankenmint

Reputation: 1632

how to send multidimensional array post data in php?

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.

Upvotes: 3

Views: 2368

Answers (3)

ArturoO
ArturoO

Reputation: 611

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.

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

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));

Upvotes: 2

Professor Abronsius
Professor Abronsius

Reputation: 33813

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 );

?>

Upvotes: 0

Related Questions