If you want a function that will return the result of a PhantomJS script, you may find this handy.
It takes an array of options to be passed as arguments to the phantomJS file, executes it, and returns its results.
I guess you have already installed phantomJS on your server, and configured it to run with no problems for the current user, right?
Here is the code:
<?php
/**
* To get this to work on my server for user "axxis" I had to edit /etc/sudoers and add:
* axxis ALL=(ALL) NOPASSWD: /usr/bin/phantomjs
**/
// // Enable Error Reporting
// ini_set('display_errors',1);
// ini_set('display_startup_errors',1);
// error_reporting(-1);
// A check to see that console commands work. Displays also the current user
//$user = exec("whoami");
//echo "Current user: ".$user;
// the important stuff...
function callPhantom($options) {
$proxySettings = isset($options['proxy']) ? $options['proxy'] : ''; //"--proxy=ip:port --proxy-type=https";
$scripttoload = $options['phantomfile']; // phantomjs script that loads the url
$URLtoload = $options['url']; // the url with the jacascript
$Referer = isset($options['referer']) ? $options['referer'] : ''; //'Me';
$UserAgent = isset($options['useragent']) ? $options['useragent'] : ''; //'MyBrowser';
if ($options['args']) { // any args you want to send to the loaded url, eg. time=198322
$args = '';
foreach ($options['args'] as $arg) {
$args .= escapeshellarg($now); // Don't forget to escape args!
}
} // To grab the args in the js file, that's another story (and another article!) ;)
$cmd = 'phantomjs' . ' '
. $proxy . ' '
. "--web-security=no" . ' '
. $scripttoload . ' '
. $args . ' '
. escapeshellarg($URLtoload) . ' '
. escapeshellarg($Referer) . ' '
. escapeshellarg($UserAgent) . ' '
. ' 2>&1'; // let's capture STDERR as well
// execute phantomjs script, let the javascript on this page execute,
// and get the finished page in a variable: $code_of_loaded_content
exec($cmd, $op, $er);
$code_of_loaded_content = implode("",$op);
if (!empty($er)) {
echo "<h1>ERRORS</h1>";
echo $er;
}
//echo "<h1>RESULT</h1>";
return $code_of_loaded_content;
}
// EXAMPLE
/*
echo callPhantom(array(
'phantomfile' => DIRNAME(__FILE__).'/take_screenshot.js',
'url' => 'http://chrismichaelides.eu/'
));
*/
?>
The function passes the given options over to the phantom js file, but to see how they are being handled, you'll have to wait for the next article! :)





