Phantomjs - Is there a way to pass parameters to th

痞子三分冷 提交于 2019-12-10 10:15:19

问题


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?


回答1:


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.




回答2:


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



回答3:


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;


来源:https://stackoverflow.com/questions/17026127/phantomjs-is-there-a-way-to-pass-parameters-to-th

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!