无法将 post 值传递给 curl

can't pass the post value to curl

这是我的code.In这种情况,它不会用post值($con)在$cmd

中输入文本
  <?php
  if(isset($_POST['conversation']))
  {
  $con=$_POST['conversation'];
  echo $con;
  $cmd='curl -X POST -u "username":"password" -H "Content-Type:application/json" -d "{\"input\": {\"text\":\"$con\"]}}""https://gateway.watsonplatform.net/conversation/api/v1/workspaces/a9379972-d820-4cdf-b1cb-ad0af898a534/message?version=2016-07-11"';
  exec($cmd,$result);
 //$response = json_decode($result);
 print_r($result);
 }
 ?>

您正在使用原始 POST 值并将其作为命令行参数传递。这是一个糟糕的主意。它使您很容易受到远程执行攻击。有人可以轻松 post 对话值“; sudo rm -rf /”。坏消息。不转义输入几乎肯定会破坏您尝试发送的 JSON 散列。

接下来,您的 POST 数据和 URL 之间缺少 space,因此 curl 甚至看不到 URL。

如果您需要执行命令行版本的 curl,请对您的值使用 escapeshellarg

理想情况下,使用 PHP curl 库。 http://php.net/manual/en/book.curl.php 然后您可以以编程方式使用 curl,您不必担心生成 curl 进程或如何转义 args。

注意 ' 和 " 的使用。您将 $con 括在单引号中,所以它没有被解析:

$bob = 'hello';
$a = '$bob';
$b = "$bob";

$a : $bob
$b : hello

只需使用 PHP 的 built-in curl commands:

<?php
if(isset($_POST['conversation'])) {
    $data = array("input"=>array("text"=>$_POST["conversation"]));
    $url = "https://gateway.watsonplatform.net/conversation/api/v1/workspaces/a9379972-d820-4cdf-b1cb-ad0af898a534/message?version=2016-07-11";
    $ch = curl_init($url);
    curl_setopt_array($ch, array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_USERPWD => "username:password",
        CURLOPT_HTTPHEADER => array("Content-Type:application/json"),
        CURLOPT_POSTFIELDS => json_encode($data),
    ));
    $response = curl_exec($ch);
    curl_close($ch);
    print_r(json_decode($response));
}
?>