How to execute a PHP program in the form of a string inside node.js?

Viewed 395

I get a PHP string from the frontend and I just want to execute it and get the stdout and stderr.

This is what I tried:

const runner = require('child_process');
runner.exec('php ' + phpString, (err, stdout, stderr) => {
  // ...
});

but this requires the PHP code to be in a file because it needs the path as an argument which leads to a PHP file. But writing the phpString to a file and then executing it seems unnecessary so is there a way I can directly execute the string?

2 Answers

You can use -r flag of PHP cli for that.

const runner = require('child_process');
const phpString = `'echo "hi";'`
runner.exec('php -r ' + phpString, (err, stdout, stderr) => {
     console.log(stdout) // hi
});

Although I would use execFile/spawn instead, to avoid scaping the arguments

const runner = require('child_process');
const phpString = `echo "hi";` // without <?php
runner.execFile('php', ['-r', phpString], (err, stdout, stderr) => {
   console.log(stdout) // hi
});

If you want to use <?php tags, you should use spawn and write to stdin. This is the best approach in my opinion.

const php = runner.spawn('php');
const phpString = `<?php echo "hi";?>` // you can use <?php

// You can remove this if you want output as Buffer
php.stdout.setEncoding('utf8') 
php.stdout.on('data', console.log)
php.stderr.on('data', console.error)

php.stdin.write(phpString)
php.stdin.end()

Have in mind that allowing users to execute code on your server is not recommended.

Marcos already gave a valid and correct answer, I would just like to add that you can also pipe the php-code to the php-executable:

const { exec } = require('child_process');

const phpString = '<?php echo 1; ?>';

exec(`echo "${phpString}" | php`, (error, stdout, stderr) => {
  console.log(stdout); // prints "1"
});
Related