CasperJS is built on top of PhantomJS (or SlimerJS). It can use all the features PhantomJS provides which includes the Web Server Module. The idea would be to run a single CasperJS instance which your PHP script can query through HTTP.
You can start a CasperJS script at system startup or through a cron job (and restarting when it crashes). You can then query it through local http requests.
CasperJS script:
var webserver = require('webserver');
var server = webserver.create();
var service = server.listen(8080, function(request, response) {
var casper = require('casper').create({
exitOnError: false,
onError: function(msg, backtrace){
response.statusCode = 500;
response.write('ERROR: ' + msg + "\n" + JSON.stringify(backtrace));
response.close();
}
});
casper.start(yourURL, function(){
// TODO: do something
response.statusCode = 200;
response.write('something');
response.close();
}).run(function(){
// this function is necessary to prevent exiting the whole script
});
});
And in PHP you can then use something like file_get_contents() to retrieve the response:
$result = file_get_contents("http://localhost:8080/");
Things to look out for:
- Configure your machine in such a way that the port PhantomJS is running on is not accessible from outside.
- If you're using a cron job approach, write a pid file to make sure not to start another instance.
- The web server module only supports 10 concurrent requests. If your system exceeds those, you will need to create a pool of multiple CasperJS (PhantomJS) processes.
- The pages of a single CasperJS (PhantomJS) process all share the same session just like in any normal browser. If you want to isolate them from one another, then you need to run a CasperJS (PhantomJS) process for every request.