2
votes

Ubuntu 18 VM in AWS.

$return = exec("node -v", $o, $e);
var_dump($retu);
var_dump($o);
var_dump($e);

Output:

string(8) "v10.16.3" array(1) { [0]=> string(8) "v10.16.3" } int(0)

  1. So node is installed properly.
  2. exec is able to get node version.

However, $return = exec("node /var/www/savePdf.js someUrl someName", $o, $e); is not working.

Output:

string(0) "" array(0) {} int(1)

node /var/www/savePdf.js someUrl someName is working in the terminal, the PDF file is generated and getting saved properly. How can this issue be addressed?

<?php echo exec('whoami'); ?> outputs as nt authority\system

The var/www -R is owned by www-data.

On researching some tutorials I added the following lines to sudoers file (ignoring the warnings mentioned there about the security, so that I can sudo the exec command),

enter image description here

$return = exec("sudo node /var/www/savePdf.js someUrl someName", $o, $e); // no difference

The savePdf.js contains GoogleChrome/puppeteer code for generating PDF from URL as follows,

'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();
})();
2
In your JS. Can you use console.log and try & catch to track the run-time error? - BadPiggie
@Banujan, thank you so much! It is fixed after adding > /dev/null &. However, It takes 3 to 4x times to generate the PDF when calling from exex/shell_exec compared to terminal. - Mr Cathode

2 Answers

0
votes

Because the exec() won't wait until your script complete the execution,

You need to execute following command to let exec() to wait,

 $return = exec("node /var/www/savePdf.js someUrl someName  > /dev/null &", $o, $e);

NOTE

The php function exec() only returns the last line of result, while shell_exec() returns the complete result.

Reference

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/

0
votes

Thanks to Banujan Balendrakumar for this answer.

Adding > /dev/null & will work in this case.

exec("node /var/www/savePdf.js someUrl someName > /dev/null &", $o, $e);

Note: There is a difference in time taken for the script to generate and save the PDF when tried from terminal and from PHP.