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=:0to 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 &andexport DISPLAY=:40before executing pantomjs
Here’s the final script that worked great on my local PHP / Linux install:
$screenshot_file_name = "thumbs/screen1.jpg";
$website_address = 'http://example.com';
$screenshot_file_name = realpath($screenshot_file_name);
$script = "var page = require('webpage').create();
page.viewportSize = {
width: 1600,
height: 1400
};
page.open('$website_address', function () {
window.setTimeout(function () {
page.render('$screenshot_file_name');
phantom.exit();
}, 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");
if(filesize($screenshot_file_name)){
echo "<br>Screenshot saved: $screenshot_file_name ";
}else{
echo "<br>Warning:! Screenshot $screenshot_file_name failed to generate <br>\n";
}
unlink($file);