0

I am calling to a PHP file, from a nodejs app and sending argument, while one of the arguments should be JSON (stringified of course)

It isn't working as expected, as the string appears to be multiple arguments and need to be escaped or correctly.

Trying to split the problem, I created a new php file, trying to execute from the outside (in this example from command line) ->

running the following command

php test.php {"access_token":"acccess_token","id_token":"id_token","refresh_token":"refresh-token","token_type":"token_type","expiry_date":1515578624982,"expires_in":3600}

here is the code sample that is failing

<?php
$json = $argv[1];

$res = json_decode($json,true);
echo "CHECK-ERROR".json_last_error().PHP_EOL."-----".PHP_EOL;

echo "END RESULTS".PHP_EOL.$res.PHP_EOL."-------".PHP_EOL;

?>

here is the output

enter image description here

so few interesting facts: - Changing the code to have the argument as a local variable - works fine. - putting the json in single quotes '{...}' - works fine. - calling the php from the NodeJS using '${jsonStringified}' - works fine. (as it the same idea as the abovemnetinoed

The question is what other solutions exists? (e.g. encoding, escaping) rather than this small tweak?

rabashani
  • 1,443
  • 2
  • 14
  • 22

1 Answers1

0

First, you haven't defined $argv[1]. Second, it's not JSON in the eyes of PHP, it's a string, so it needs to be JSON Encoded, before PHP reads it.

Command line:

php test.php "{ \"access_token\": \"acccess_token\", \"id_token\": \"id_token\", \"refresh_token\": \"refresh-token\", \"token_type\": \"token_type\", \"expiry_date\": 1515578624982, \"expires_in\": 3600 }"

PHP script:

$json = json_decode($_SERVER['argv']['1'], true);

if (json_last_error()) { var_dump($_SERVER['argv']['1']); die(); }

echo "CHECK-ERROR".json_last_error().PHP_EOL."-----".PHP_EOL;

echo "END RESULTS".PHP_EOL.json_encode($json).PHP_EOL."-------".PHP_EOL;

Should do the trick.

Anuga
  • 2,619
  • 1
  • 18
  • 27
  • 1) [`$argv` documentation](http://php.net/manual/en/reserved.variables.argv.php) 2) JSON *is* a string, by definition, and OP is already decoding it as such. – deceze Jan 10 '18 at 13:06
  • Never trust setttings dependent variables: http://php.net/manual/en/ini.core.php#ini.register-argc-argv – Anuga Jan 10 '18 at 13:08
  • Sure, but you don't know enough here to categorically state that `$argv` isn't defined. – deceze Jan 10 '18 at 13:10
  • Using $_SERVER, I don't need to know ;) – Anuga Jan 10 '18 at 13:10