0

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

  • Having to save the file to disk
  • Installing additional PHP extensions (such as V8js)

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.

1
  • You should be able to pipe code to Node and have the results, if any, streamed back. Be extremely careful when allowing people to execute arbitrary code on your system. I'd want this sandboxed aggressively. Commented Oct 13, 2016 at 1:49

1 Answer 1

1

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...

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

Comments

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.