Wednesday, September 9, 2015

Using PhantomJS on Shared Hosting like HostGator

Installing PhantomJS

If you are a shared account Hostgator user you know that Hostgator locks down your account fairly well. You don’t have access to install anything on your machine and if CPanel doesn’t give you an option you are back to square one. Well luckily for us, the awesome people at PhantomJS provide us with an already compiled binary file for CentOS linux servers. This is awesome news because Hostgator uses CentOS linux servers for shared hosting.
A binary file is like a .exe file in Windows. That one file contains a whole program all you have to do is “execute” the program (equilavent to a double click with a mouse).
All we have to do is download the PhantomJS binary for CentOS 32 Bit and upload/ftp that binary file to your hosting account.
Incase you missed the link above, download the binary from here:http://phantomjs.org/download.html

Running PhantomJS in Command Line

I would suggest moving the PhantomJS binary file to your home directory. Once there, you can executePhantomJS by simply pointing to the file: ~/phantomjs -v.
Note: Since you do not have permission to expose a program globally on shared hosting. You must use the PATH to PhantomJS in order to execute the program. e.g. /path/to/phantomjs -v
If you are not familiar with PhantomJS yet you may not know that PhantomJS needs a javascript program passed to it in it’s first parameter. If you visit PhantomJS’ github page you can obtain a folder full of example javascript programs.
Personally, I decided to make a folder in my home directory called phantomJSPrograms. So when I runPhantomJS from my home directory my command looks something like this.
./phantomjs phantomJSPrograms/rasterize.js http://arlocarreon.com arloBlog.png
The above command will render a screenshot of my blog.

Running PhantomJS in PHP

If you know how to run PhantomJS in command line then nothing changes in PHP, with the exception of 1 caveat.
  1. First practice in command line until you know exactly what command you want to run.
  2. [Caveat] – You must end all your commands with 2>&1. This is because PhantomJS returns some messages as error messages via stdout 2, so we need to pipe all stdout 2 messages to stdout 1. Our php methods return output from stdout 1.
  3. Use any php method you feel comfortable with for executing shell commands. execpassthrushell_exec,systembackticks, etc.

Demo

This is a demo to the app I was putting together. It periodically takes screenshots of our client’s sites and you can also manually reload the screenshot of any site. It uses a AJAX call to run a PHP script that runs PhantomJS.
http://www.arlocarreon.com/blog/javascript/using-phantomjs-on-shared-hosting-like-hostgator/