简体   繁体   中英

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.
The PHP function receive json encoded data and the url as variables.
I am trying to build the string to be sent to shell_exec command using the above variables.

As you can see in sample code below, the first string ($cmd) has $jsonDataEncoded as variable (the url is clear text). This string works fine with the shell_exec command, and json data are returned from the server.

The second one ($cmd1) has both $jsonDataEncoded and $url as variables. This string DOES NOT work with shell_exec command.

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. You can use a libary for that:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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