1



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;
}

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

The reason I do not use curl libraries is that they works fine on localhost but they do no work at all on the linux server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.