rodrigo-silveira
rodrigo-silveira

Reputation: 13068

PHP exec node dynamic script from memory

I'm trying to run code through Node.js from PHP without touching the file system (the disk). Is this possible?

What I'm doing

<?php

function renderJs($script) {
  $path = __DIR__.'/'.md5($script).'.js';
  file_put_contents($path, $script);
  $rendered = `node $path`;
  unlink($path);

  return $rendered;
}

$val = renderJs('console.log(1+1)'); // 2

What I'd like to avoid

Ideally, it'd be something like

$magicBlob = php_magic($script);
$rendered = `node $magicBlob`;

I can't just eval it as in

$rendered = `node --eval "$script"`;

because the script might have quotes that would break my outer quoting.

Upvotes: 0

Views: 92

Answers (1)

ThePengwin
ThePengwin

Reputation: 822

using escapeshellarg works for me:

$js = <<<EOF

hello = function (name) {
    console.log('`Hello there '+name+"!!`");
}

hello('PHP');
EOF;

$rendered = system("node --eval ".escapeshellarg($js));

I don't know how good of an idea that is, but...

Upvotes: 1

Related Questions