简体   繁体   English

如何在 node.js 中以字符串形式执行 PHP 程序?

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

I get a PHP string from the frontend and I just want to execute it and get the stdout and stderr.我从前端得到一个 PHP 字符串,我只想执行它并获取标准输出和标准错误。

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.但这需要 PHP 代码在文件中,因为它需要路径作为参数,从而导致 PHP 文件。 But writing the phpString to a file and then executing it seems unnecessary so is there a way I can directly execute the string?但是将phpString写入文件然后执行它似乎没有必要所以有没有办法可以直接执行字符串?

You can use -r flag of PHP cli for that.您可以为此使用PHP cli 的-r标志。

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虽然我会改用execFile/spawn ,但为了避免避开 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 .如果你想使用<?php标签,你应该使用spawn并写入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: Marcos 已经给出了有效且正确的答案,我想补充一点,您也可以将php php -code 转换为php -executable:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM