PHP + PhantomJS Rasterize

2019-02-27 16:45发布

问题:

I'm using PhantomJS 64 bit in my PHP application to dynamically capture an HTML page to be emailed to the user.

phantomjs rasterize.js "http://..." /path_to_images/image.png

This method works fine when I run the above on the command line but when the PHP script runs the command using exec it fails with no output and returns exit code 11.

If I switch it to use the 32 bit phantomJS binary, the command succeeds but fails to load the google JSAPI on the page since with error Reference Error: can't find variable google. This is a problem because not all of the page content is loaded and captured as an image. The JSAPI is included using HTTPS. If I switch to HTTP, the reference error is gone but the rendered image comes out all black.

I tested the command as the same user that php is running as.

To sum it up:

command> phantomjs_64 rasterize.js "http://..." /path_to_images/image.png

OK

exec('phantomjs_64 rasterize.js "http://..." /path_to_images/image.png');

No Output, Exit Code 11

command> phantomjs rasterize.js "http://..." /path_to_images/image.png
exec('phantomjs rasterize.js "http://..." /path_to_images/image.png');

Incomplete Output

Does anyone know why the default phantomJS rasterize.js script would fail when running on PHP or have a workaround for this?

回答1:

UPDATE: This great article by Arlo Carreon points out how to make this work on HostGator shared hosting (this was my problem). Simply add 2>&1 at the end of the command to redirect the output. The 64 bit version still does not work but this fixes the 32 bit version.

It turns out that this only happens when the PHP script is requested through the Apache web server. The workaround is to create a database entry for users that need to receive the email and setup a cron to execute the PHP script that calls PhantomJS for each user entry in the DB. When the cron is set to run at the smallest interval the user perceives that the email was generated and sent immediately.