Search code examples
phpwkhtmltopdfshell-exec

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


I'm in trouble and that much confused about a php shell_exec command. When the command is execute by PHP I have no error but the execution fails. If I use exactly the same command from a terminal it works.

Here's the command :

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

When I lauch this from a terminal :

$ /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      

But from my php script :

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

I've test the output of shell_exec, it's empty.

The log :

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

No permission pb in the /tmp directory :

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

I've tried avec the PHP exec() function to get error informations, I just get an "1" error code in return_var and nothing in output.

For information this issue appear on my test server, my desktop computer but not on my notebook. All the 3 are with sames PHP, Apache, Mysql versions. I don't understand anything ...

Thanks for any help, I'm loosing my mind. David.


Solution

  • I've found the solution here : Executing wkhtmltopdf from PHP fails

    Thanks to Krzychu.

    First to get information from the shell_exec command add " 2>&1" at the end of the command. In that way you will get information in return of the command :

    $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"
    

    The solution :

    1. Not use the wkhtmltopdf ubuntu package (0.9.9-4)

    2. Use the official package from the Wkhtmltopdf download page

    So no need to install xvfb ! (I've seen this advice many times)