AWS中的Ubuntu 18 VM。
$return = exec("node -v", $o, $e);
var_dump($retu);
var_dump($o);
var_dump($e);
输出:
string(8)“ v10.16.3” array(1){[0] => string(8)“ v10.16.3”} int(0)
但是,$return = exec("node /var/www/savePdf.js someUrl someName", $o, $e);
无法正常工作。
输出:
string(0)“” array(0){} int(1)
node /var/www/savePdf.js someUrl someName
在终端中工作,PDF文件已生成并正确保存。 如何解决此问题?
<?php echo exec('whoami'); ?>
输出为nt authority\system
var/www -R
由www-data
拥有。
在研究一些教程时,我在sudoers文件中添加了以下几行(忽略那里提到的有关安全性的警告,以便我可以对exec命令进行sudo)
$return = exec("sudo node /var/www/savePdf.js someUrl someName", $o, $e); // no difference
savePdf.js包含GoogleChrome/puppeteer
代码,用于从URL生成PDF如下,
'use strict';
const puppeteer = require('/var/www/mysitename/public_html/node_modules/puppeteer');
const url = process.argv[2], name = process.argv[3];
(async() => {
const browser = await puppeteer.launch(
{
executablePath: '/usr/bin/google-chrome',
args: ['--no-sandbox', '--disable-setuid-sandbox']}
);
const page = await browser.newPage();
await page.goto(url, {waitUntil: 'networkidle2'});
await page.pdf({
path: '/var/www/mysitename/public_html/resources/logs/'+name+'.pdf',
format: 'A4',
printBackground: true,
margin: {
top: "1cm",
bottom: "1cm",
left: "1cm",
right: "1cm",
}
});
await browser.close();
})();
答案 0 :(得分:0)
因为exec()
不会等到脚本完成执行,
您需要执行以下命令来让exec()
等待
$return = exec("node /var/www/savePdf.js someUrl someName > /dev/null &", $o, $e);
注意
php函数 exec()仅返回最后一行,而 shell_exec()返回完整结果< / strong>。
参考
https://www.geeksforgeeks.org/php-shell_exec-vs-exec-function/
https://subinsb.com/how-to-execute-command-without-waiting-for-it-to-finish-in-php/
答案 1 :(得分:0)
在这种情况下,添加> /dev/null &
即可。
exec("node /var/www/savePdf.js someUrl someName > /dev/null &", $o, $e);
注意:在终端和PHP上尝试运行脚本时,脚本生成和保存PDF的时间有所不同。