Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 284
Frankenmint Avatar asked Sep 03 '26 12:09

Frankenmint


1 Answers

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));
like image 165
u_mulder Avatar answered Sep 05 '26 02:09

u_mulder