php shell_exec не работает с кукловодом

  • Веб-сервер: nginx
  • PHP-фреймворк: Laravel 5.5
  • Библиотека для создания PDF: puppeteer

Итак, что я хочу сделать, так это то, что когда пользователь нажимает кнопку Загрузить, сервер делает следующее:

  1. Создание HTML-файла с содержимым
  2. запустите следующий код

Контроллер Laravel

$shell_output = shell_exec('`which node` ' . base_path('bin/export.js') . ' ' . $html_file . ' ' . $pdf_file . ' A4');
print($shell_output); // <------- empty output

$workable_output = shell_exec('echo `which node`');
print($shell_output); // <------- THIS IS SHOWING "/usr/local/bin/node"

содержание export.js

const puppeteer = require('puppeteer');

var filename = process.argv[2];
var output = process.argv[3];

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setViewport({ width: 1000, height: 1415 });
  await page.goto('file://' + filename, { waitUntil: 'networkidle2' });
  await page.emulateMedia('print');
  await page.pdf({
    path: output,
    format: 'A4',
    printBackground: true,
    landscape: false,
    margin: {
      top: '60px',
      right: '20px',
      bottom: '30px',
      left: '20px'
    }
  });

  await browser.close();
})();

Но проблема в том, что файл PDF не создается, а $shell_output тоже пуст.

Затем я пытаюсь запустить команду оболочки в терминале, и она отлично работает. то есть

$ `which node` export.js content.html content.pdf A4

Опять же, я попытался создать файл php и запустить его с помощью php-cli, т.е.

$ php test.php

содержимое test.php, как показано ниже

<?php
$shell_output = shell_exec('env DEBUG="puppeteer:*" `which node` export.js content.html content.pdf A4');
echo $shell_output;

Журнал сервера

/var/log/nginx/error.log

2018/03/13 10:37:05 [error] 13017#13017: send() failed (111: Connection refused) while resolving, resolver: 127.0.0.1:53

P/S: я размещаюсь в AWS EC2. Это не проблема, когда я запускаю на локальной машине.

Обновление от 14 марта 2018 г., 14:55 (UTC+8)

Я попытался поместить код в папку с тестами в Laravel.

./tests/Unit/ExampleTest.php

$shell_output = shell_exec('`which node` ' . base_path('bin/export.js') . ' ' . $html_file . ' ' . $pdf_file . ' A4');

И запустите с пользователем ubuntu, это работает

ubuntu@ip-xxx-xx-xx-xx:/var/www/project$ ./vendor/phpunit/phpunit/phpunit --filter ExampleTest
PHPUnit 6.3.0 by Sebastian Bergmann and contributors.

.
.                                                                  2 / 2 (100%)

Time: 4.82 seconds, Memory: 14.00MB

НО, когда я пытаюсь запустить с пользователем www-data, это не удается

ubuntu@ip-xxx-xx-xx-xx:/var/www/project$ sudo -u www-data ./vendor/phpunit/phpunit/phpunit --filter ExampleTest
PHPUnit 6.3.0 by Sebastian Bergmann and contributors.

.(node:7991) UnhandledPromiseRejectionWarning: Error: spawn EACCES
    at ChildProcess.spawn (internal/child_process.js:330:11)
    at Object.exports.spawn (child_process.js:500:9)
    at Function.launch (/var/www/project/node_modules/puppeteer/lib/Launcher.js:106:40)
    at <anonymous>
(node:7991) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7991) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
.                                                                  2 / 2 (100%)

Time: 276 ms, Memory: 14.00MB

OK (2 tests, 2 assertions)

Есть идеи, где проблема?


person Js Lim    schedule 13.03.2018    source источник


Ответы (1)


Я нашел проблему, она вызвана самим исполняемым файлом chrome

Решено

$ chmod 777 /var/www/project/node_modules/puppeteer/.local-chromium/linux-536395/chrome-linux/*

Найдено из выпуска GitHub.

person Js Lim    schedule 14.03.2018