How to run PhantomJS from PHP

I was adding PhantomJS into an existing PHP script and running passthru('phantomjs .....'); just wasn’t working.

A few tips:

  • If you’re running the script locally, add export DISPLAY=:0 to the PHP passthru()
  • If you’re running the script on a remote host make sure someting like Xvfb is installed, then run nohup Xvfb :40 -ac -screen 0 1600x4000x24 & and export DISPLAY=:40 before executing pantomjs

Here’s the final script that worked great on my local PHP / Linux install:


$screenshot_file_name = "thumbs/screen1.jpg";
$website_address = '';
$screenshot_file_name = realpath($screenshot_file_name);
$script = "var page = require('webpage').create();
page.viewportSize = {
 width: 1600,
 height: 1400
};'$website_address', function () {
 window.setTimeout(function () {
 }, 1000); // Change timeout as required to allow sufficient time 
$file = "/tmp/phantom".md5($website_address).'.js';
file_put_contents($file, $script);
passthru("export DISPLAY=:0 && phantomjs $file && convert $screenshot_file_name -resize 406x -crop 400x300+0+0 +repage $screenshot_file_name.thumb.jpg");
 echo "<br>Screenshot saved: $screenshot_file_name ";
 echo "<br>Warning:! Screenshot $screenshot_file_name failed to generate <br>\n";


Leave a Reply

Your email address will not be published. Required fields are marked *