Search code examples
arraysjsonnightmare

Pass PHP Array to NodeJS


How do I pass a PHP array to a Nightmare NodeJS script? This is where I'm at:

 /*Original array $titles = 
 Array
 (
 [0] => title 1 with, a comma after with
 [1] => title 2
 [2] => title 3
 [3] => title 4
 )
 */

//PHP
$json_titles = json_encode($titles);
echo $json_titles;
//  Output:  ["title 1 with, a comma after with","title 2","title 3","title 4"]
// Pass to Nightmare NodeJS script with:
shell_exec('xvfb-run node app.js ' . $json_titles);

//NodeJS app.js:

const getTitles = process . argv[2];
console.log(getTitles)

// Output: [title 1 with, a comma after with,title 2,title 3,title 4]

How do I get the same array in PHP to NodeJS?

As you see below Simon came to the rescue with escapeshellarg. Thanks Simon! I also ended up having one more step in the Node JS script. I needed to: getTitles = JSON.parse(getTitles);


Solution

  • Change your shell_exec to escape the json like so:

    shell_exec('xvfb-run node app.js ' . escapeshellarg($json_titles));
    

    This escapes the double quotes in your JSON so they are passed correctly to node.

    You should do this any time you pass variables to the command line, to reduce bugs and security risks.

    Edit: as discovered by OP, Node will also have to parse the JSON since it gets the argument as a string. This can be done in the node script as follows:

    ParsedTitles = JSON.parse(getTitles);