Using PhantomJS on Shared Hosting like HostGator
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
.exefile 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
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.
Personally, I decided to make a folder in my home directory called
phantomJSPrograms. So when I run PhantomJS 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.
- First practice in command line until you know exactly what command you want to run.
- [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.
- Use any php method you feel comfortable with for executing shell commands. exec, passthru, shell_exec, system, backticks, etc.
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.