4

Edit: I answered my own question, see edit below.

ORIGINAL: I have phantomjs and casperjs installed on my web server and they both run fine. The script I am planning on creating relise on a user input from my website, which is then passed on to the casperjs script. After fiddling around a bit, I noticed that I am stuck on the very basic task of the user input. How would pass the variable from php to casperjs?

Please note, the following are just test scripts.

My php script

$user_input = $_POST['user_input'];

putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");
exec('/usr/local/bin/casperjs hello.js 2>&1',$output);
print_r($output);

hello.js

var user_input = "http://example.com/";
var casper = require('casper').create({
  verbose: true,
  logLevel: 'error',
  pageSettings: {
    loadImages: false,
    loadPlugins: false
  }
});

casper.start(user_input, function() {
    this.echo(this.getTitle());
});

casper.run();

So how would I pass the $user_input to the hello.js. My goal is that the user can input a url which is then being scraped.

3
  • 2
    You can post that answer as 'Answer' and accept it. That is the proper way to do it. Commented Apr 18, 2014 at 5:12
  • Yes, please post it as self-answer. Your answer is basically correct, but use escapeshellarg (even if you know this, someone copy and pasting from your answer in future might not). (E.g. user_input = ';rm -rf /etc/' ) Commented Apr 18, 2014 at 12:46
  • I had to wait 48 hours until I could answer myself. I fixed it now. Thanks Commented May 5, 2014 at 20:25

1 Answer 1

5

I found the answer myself.

It seems phantomjs and casperjs support command line arguments http://phantomjs.org/api/system/property/args.html

My script now looks like this.

test.php

$user_input = $_POST['user_input'];

putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");
exec('/usr/local/bin/casperjs hello.js $user_input 2>&1',$output);

print_r($output);

hello.js

var system = require('system');
var args = system.args;
var address = args[4]; //In my case 4 was the argument for $user_input, yours might be different, depending on your server setup.

var casper = require('casper').create({
  verbose: true,
  logLevel: 'error',
  pageSettings: {
    loadImages: false,
    loadPlugins: false
  }
});

casper.start(address, function() {
    this.echo(this.getTitle());
});

casper.run();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.