0

Guys can you please help? I need to pass a JSON format to an API via HTTP POST.

{
"osr":{
"sa":"1111",
"ostm":{
"msg":"Hello World"
},
"addr":"192.168.0.1"
}
}

My URL is accepting these values via GET request:

https://url/api/?&cid=1234567&sender=1221&text=John%20Doe

Once the endpoint accept the values above, it will query to get the token from mysql, and pass these values to another API via HTTP POST.

$cid  = mysqli_real_escape_string($mysqli,$_GET["cid"]);
$sender  = mysqli_real_escape_string($mysqli,$_GET["sender"]);
$text  = mysqli_real_escape_string($mysqli,$_GET["text"]);

$mysqli_result = mysqli_query($mysqli,"SELECT `cid`,`token` FROM `store` WHERE cid='$cid' AND sender='$sender' AND hold='0';");
$row = mysqli_fetch_row($mysqli_result);

if ($mysqli_result->num_rows > 0) {
        $cidres     = $row[0];
        $tokenres   = $row[1];

        extract($_POST);
                $text   = $_GET['text'];
                $cid    = $_GET['cid'];

        $url = "https://api/".$sender."/requests?access_token=".$token."";
        $fields = array(
                'sa'=>urlencode($sender),
                'msg'=>urlencode($text),
                'addr'=>urlencode($cid),
        );

$fields_string = '';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

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

Currently I have verified that this is working from curl, but I can't build the correct code in PHP:

curl -X POST "https://api/requests?access_token=123456" \
    -H "Content-Type: application/json" -d '{"osr":{"sa":"1111","ostm":{"msg":"Hello World"},"addr":"192.168.0.1"}}'
  • 1
    Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) ___Marie would not want you to do that___ – RiggsFolly Feb 07 '17 at 14:09
  • 1
    What's up with the `extract($_POST);` in the middle of it all? – M. Eriksson Feb 07 '17 at 14:12
  • 1
    ^^^^^^^^ Oh YUK ^^^^^^^^^^^ – RiggsFolly Feb 07 '17 at 14:12
  • 1
    Mr Webb Please look up `json_encode()` and `json_decode()` Dont try and code your own JSON – RiggsFolly Feb 07 '17 at 14:14
  • You can get the post values like this. $post = file_get_contents('php://input'); – Jose D Feb 07 '17 at 14:16

0 Answers0