php shell_exec命令不像 bash / 返回错误


php shell_exec command doesn't act like bash / returns an error

这是我的代码:

$url = escapeshellarg("http://www.mysite.com");
$command = shell_exec("xvfb-run -a -s '-screen 0 640x480x16' wkhtmltopdf --dpi 300  --page-size A4 $url /srv/www/mysite/public_html/tmp_pdf.pdf");
$str = file_get_contents("/srv/www/mysite/public_html/tmp_pdf.pdf");
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($str));
header('Content-Disposition: inline; filename="pdf.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
die($str);

在我的 bash shell(使用 Debian)中,命令

shell_exec("xvfb-run -a -s '-screen 0 640x480x16' wkhtmltopdf --dpi 300 --页面大小 A4 html://www.mysite.com/srv/www/mysite/public_html/tmp_pdf.pdf

工作,它在所需位置生成一个 PDF,但是当我在 PHP 中执行命令时,什么都没有创建,我被返回到一个空的 PDF 文件(因为它不存在)。有人可以帮我找出问题所在吗?

问题是 Apache 服务器对我试图将 pdf 写入的文件夹没有写入权限(在我的示例中为/srv/www/mysite/public_html/)。

所以我只是将文件夹位置更改为/tmp(每个人都有写入权限),现在它可以工作了。更正后的代码是:

$url = escapeshellarg("http://www.mysite.com");
$command = shell_exec("xvfb-run -a -s '-screen 0 640x480x16' wkhtmltopdf --dpi 300  --page-size A4 $url /tmp/tmp_pdf.pdf");
$str = file_get_contents("/tmp/tmp_pdf.pdf");
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($str));
header('Content-Disposition: inline; filename="pdf.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
die($str);
我不知道

你的工具在那里,所以用一公吨盐来拿这个。

如果您有该 url

并且该工具会下载该 url 本身,则可能存在一些网络权限阻止。如果您可以自己下载 url 并仅向此工具提供可能消除这种可能性的内容(或来自临时文件)。

还要检查您尝试写入其中的文件夹的权限。

既然你说 Debian,那就执行以下命令:

which xvfb-run

这将为您提供可执行文件的完整路径,我将在shell_exec调用中使用它。

至于将文件流式传输出去,我会使用readfile。

$filePath = "/srv/www/mysite/public_html/tmp_pdf.pdf";
header('Content-Type: application/pdf');
header('Content-Length: ' . filesize($filePath));
header('Content-Disposition: inline; filename="pdf.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
readfile($filePath);
exit();

优点是不需要为此将整个文件读入内存。