Back To Normal
Click Here To Subscribe Via Email

Subscribe To Our E-Mail Newsletter

Thursday, July 9, 2015

Taking Webpage Screenshots using PHP and PhantomJS


Couch ModePrint It


PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.

As the text describes, PhantomJS is a headless browser engine powered by webkit. It can be used for many tasks like, as described by its official website, Headless Website Testing, Screen Capturing (that's what we are gonna do now), Page Automation(♥) and Network Monitoring.

Screen capturing using PhantomJS is really simple; it has been also demonstrated here. But how to do with PHP? Well, that's simple too. Using PHP, we have to execute our script with PhantomJS. That's all. Simple, no?

Capturing Screenshots using PHP


The solution has been already posted by Peter Ivanov on GitHub. But this is not for shared hostings or limited environments as you need to execute PhantomJS server-side (VPS?).

Get Required Files from GitHub

  • Go to https://github.com/microweber/screen
  • Upload all files to your webserver (index.php, shot.php and /bin). For example, to directory: /var/www/html/screen/
  • Make the binary executable using commad: chmod +x /var/www/html/screen/bin/phantomjs
    (You can use latest executable)
  •  Test it by opening your browser and navigating to index.php
  • Read more about the code at GitHub 

Basic Script For Website Screenshot

The above PHP code works by using setting some $vars and then executing the following basic code.

var page = require('webpage').create();
page.open('http://github.com/', function() {
  page.render('github.png');
  phantom.exit();
});


Here the file name of the image generated will be 'github.png'. So, this is how it works. Simple code opening github.com and then generating it's screenshot. I would suggest you to dig into the php code above. That's all!



:D
:)
:[
;)
:D
:O
(6)
(A)
:'(
:|
:o)
8)
(K)
(M)