Let's say I have this code in PHP to call Phantomjs
shell_exec("phantomjs a-phantomjs-file.js");
Is there way to pass data from PHP to the phantomjs file? Some sort of commandline arguments perhaps?
Let's say I have this code in PHP to call Phantomjs
shell_exec("phantomjs a-phantomjs-file.js");
Is there way to pass data from PHP to the phantomjs file? Some sort of commandline arguments perhaps?
There is a list of command line arguments for phantomjs here: https://github.com/ariya/phantomjs/wiki/API-Reference
You can use string concatenation or interpolation to pass them from PHP, just be aware of and careful to protect against injection attacks if the arguments could ever be coming from user input.
You might be able to do something like this.
$array = array("option1"=>"Test", "option2"=>"test2"); // this is what you want in phantom
$tmp = tempnam("/path/to/tempDir/", "PHANTOM_");
file_put_contents($tmp, "var params = ".json_encode($array)."; ".file_get_contents("a-phantomjs-file.js"));
shell_exec("phantomjs ".escapeshellarg($tmp));
unlink($tmp);
Then in the phantom file you could access the properties as
params.option1
I send and receive data to and from PhantomJS with PHP like:
$command = '/path/to/phantomjs /path/to/my/script.js ' . escapeshellarg($uri);
$result_object = json_decode(shell_exec($command));
WARNING: Be sure to untaint user input to prevent others from executing code on your server!
Inside the javascript this URI variable is available as the second element of the system.args
array (the first element is the name of the script you are calling):
var system = require('system');
var uri = system.args[1];
When your javascript is done you can output a JSON variable before exiting PhantomJS:
console.log(JSON.stringify({
"status": "success"
}));
phantom.exit();
In the first lines of the PHP code in this example we already used json_decode()
to decode the plain text JSON return value into an object, so from within PHP we can access the status
variable using:
print $result_object->status;