无法通过 php 中的 shell_exec() 函数运行 wkhtmltopdf commad,但相同的命令适用于命令


Not able to run wkhtmltopdf commad through shell_exec() function in php but same command works on command line

我遇到了麻烦,对php shell_exec命令感到非常困惑。当命令由 PHP 执行时,我没有错误,但执行失败。如果我从终端使用完全相同的命令,它可以工作。

这是命令:

/usr/bin/wkhtmltopdf --lowquality --dpi 300 --encoding utf-8 "/tmp/knplabs_snappyxa9otq.html" "/tmp/knplabs_snappyv3pD7h.pdf"

当我从终端上执行此操作时:

$ /usr/bin/wkhtmltopdf --lowquality --dpi 300 --encoding utf-8 "/tmp/knplabs_snappyWG9XTd.html" "/tmp/knplabs_snappyv3pD7h.pdf"
Loading page (1/2)
Printing pages (2/2)                                               
Done      

但是从我的 php 脚本中:

// Construct the previous command
$command = $this->buildCommand($url, $path);
../..
shell_exec($command);
../..
$content = file_get_contents($path);
../..

我已经测试了shell_exec的输出,它是空的。

日志 :

Warning: file_get_contents(/tmp/knplabs_snappyv3pD7h.pdf): failed to open stream: No such file or directory in /*****/lib/snappy/SnappyMedia.class.php on line 64

/tmp 目录中没有权限 pb :

$ ls -la /tmp
total 448
drwxrwxrwt 16 root  root    4096 mars  12 21:51 .
../..

我已经尝试使用 php exec() 函数来获取错误信息,我只在 return_var 中得到一个"1"错误代码,而在输出中没有任何内容。

有关信息,此问题出现在我的测试服务器,我的台式计算机上,但不在我的笔记本电脑上。所有3个都是相同的PHP,Apache,Mysql版本。我什么都不懂...

谢谢你的任何帮助,我失去了理智。大卫。

我在这里找到了解决方案:从PHP执行wkhtmltopdf失败

感谢克日丘。

首先要从shell_exec命令获取信息,请在命令末尾添加" 2>&1"。这样,您将获得返回命令的信息:

$no_output = shell_exec($command);
echo $no_output; // nothing
$output = shell_exec($command . ' 2>&1');
echo $output; // in my case : "cannot connect to X server"

解决方案:

  1. 不使用 wkhtmltopdf ubuntu 软件包 (0.9.9-4)

  2. 使用 Wkhtmltopdf 下载页面的官方软件包

所以不需要安装xvfb! (这个建议我已经看过很多次了)

看起来像是用户的权限问题。

从终端运行命令时,当前使用的用户帐户具有正确的权限,可以在/usr/bin 中运行命令并执行特定文件。

当您从 php 脚本运行它时,它是系统上的 http 服务器帐户,它需要执行/usr/bin 中文件的权限。通常这是 apache 用户。

如何设置权限取决于您的系统。请记住,Apache允许的,允许任何访问您的http服务器的人都可以使用。

我已经有这个问题很长时间了,并添加了. ' 2>&1'之后$command以某种方式解决了问题。

这:

$output = shell_exec($command . ' 2>&1');

而不是:

$output = shell_exec($command);

不知道为什么,但它有效,我很感激。

它是共享主机吗?似乎shell_exec是一个受限制的功能。在调用shell_exec之前尝试运行error_reporting(E_ALL); ini_set('display_errors', 1);

我偶然发现了同样的问题,在我的情况下,exec 命令中的绝对路径(如/var/www)不起作用,我不得不从我执行 php 文件的位置使用相对路径。

我还想注意,它使用 shell_exec 不起作用,但是它使用正常的 exec 命令工作,不确定这里的区别在哪里。