简体   繁体   English

PHP shell_exec($cmd) 命令不适用于变量

[英]PHP shell_exec($cmd) command not working with variables



I have a php script that run an http post request with json data using the shell_exec command.我有一个 php 脚本,它使用 shell_exec 命令运行带有 json 数据的 http 发布请求。
The PHP function receive json encoded data and the url as variables. PHP function 接收 json 编码数据和 Z572D4E421E5E6B9BC111D815E8A20 作为变量。
I am trying to build the string to be sent to shell_exec command using the above variables.我正在尝试使用上述变量构建要发送到 shell_exec 命令的字符串。

As you can see in sample code below, the first string ($cmd) has $jsonDataEncoded as variable (the url is clear text).正如您在下面的示例代码中看到的,第一个字符串 ($cmd) 具有 $jsonDataEncoded 作为变量(url 是明文)。 This string works fine with the shell_exec command, and json data are returned from the server.该字符串与 shell_exec 命令配合良好,并且从服务器返回 json 数据。

The second one ($cmd1) has both $jsonDataEncoded and $url as variables.第二个 ($cmd1) 将 $jsonDataEncoded 和 $url 作为变量。 This string DOES NOT work with shell_exec command.此字符串不适用于 shell_exec 命令。

I have tried to compare both strings, even with hexadecimal compare, and they seem qite the same.我试图比较两个字符串,即使是十六进制比较,它们看起来很相似。
Thank you for your suggestion.谢谢你的建议。

Here is the code:这是代码:

    function HttpPost ($url, $jsonDataEncoded)
{
//$url=https://cloud.sample.com/web/api2/v1/auth/login
//$jsonDataEncoded= my encoded json string.

//the following string is working
$cmd = "curl -X POST -H \"Content-Type: application/json\" \
 -d '".$jsonDataEncoded. "' \
 https://cloud.sample.com/web/api2/v1/auth/login";

//the following string is NOT working
$cmd1 = "curl -X POST -H \"Content-Type: application/json\" \
 -d '".$jsonDataEncoded. "' \ ". $url;

$result = shell_exec($cmd);//WORKS
//$result = shell_exec($cmd1);//FAILS
$json = json_decode($result, true);
return $json;
}

You should remove the last \ character, it expects input on a new line.您应该删除最后一个\字符,它需要在新行上输入。 So this should work:所以这应该工作:

$cmd1 = "curl -X POST -H \"Content-Type: application/json\" \
 -d '" . $jsonDataEncoded . "' " . $url;

By the way, using shell_exec isn't a proper way to send POST requests in PHP.顺便说一句,使用 shell_exec 不是在 PHP 中发送 POST 请求的正确方法。 You can use a libary for that:您可以为此使用库:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM