Home » Php » javascript – Starting phantomjs server from php and waiting for it's response

javascript – Starting phantomjs server from php and waiting for it's response

Posted by: admin July 12, 2020 Leave a comment

Questions:

I wanted to run a phantomjs server from my php script, then do a curl request to it and read it’s response (which in the final version will give a path to generated pdf). When running phantomjs server file from the console and then navigating to it’s address in the browser, everything works fine. That’s the server.js file :

var server, service, page = require('webpage').create(), address, output,
    html = '<!DOCTYPE><html><head></head><body><h1>FOOO</h1></body></html>';

server = require('webserver').create();

var rasterize = function(html, callback){
    address = 'http://localhost';
    output = '/Users/me/print.pdf'
    page.viewportSize = { width: 600, height: 600 };
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
        } else {
            window.setTimeout(function () {
                page.content = html;
                page.render(output);
                callback();
            }, 2000);
        }
    });
}

service = server.listen(8080, function (request, response) {
    response.statusCode = 200;

    rasterize(html, function(){
        response.write('<h1>BAR</h1>');
        response.close();
        phantom.exit();     
    });
});

Basically I’m opening localhost addres, switching content of the page to my html string and then saving rendered page as pdf.

Now comes my php script :

<?
    function send_callback($data){
        echo '{type: success, data: '.$data.'}';
    }

    function curl_post($url, array $post = NULL, array $options = array()) { 
        $defaults = array( 
            CURLOPT_POST => 1, 
            CURLOPT_HEADER => 0, 
            CURLOPT_URL => $url, 
            CURLOPT_FRESH_CONNECT => 1, 
            CURLOPT_RETURNTRANSFER => 1, 
            CURLOPT_FORBID_REUSE => 1, 
            CURLOPT_TIMEOUT => 5, 
            CURLOPT_POSTFIELDS => http_build_query($post) 
        ); 

        $ch = curl_init(); 
        curl_setopt_array($ch, ($options + $defaults)); 
        if( ! $result = curl_exec($ch)) { 
            trigger_error(curl_error($ch)); 
        } 
        curl_close($ch);
        send_callback($result);
    }

        shell_exec('phantomjs '.escapeshellarg(dirname(__FILE__).'/server.js'));
        //wait to allow server to start
        sleep(5);

        $data = array('html'=> 'foo');    
        curl_post('http://localhost:8080', $data);
?>

Also no magic here. I execute phantomjs server.js command in terminal, and after 5s (time to init the server) do a curlPOST request to it.
Now I have two cases :

  • If I run php script from console, with php script.php the server starts as I can see the process running and the icon is visible in the dock, but I never get any response from it and the pdf is not created.
  • If I run the script from the browser, icon is not visible in the dock so the server starts in some other way. Still no response nor pdf.

Can anyone see anything wrong in my code or think of any ways of debugging it ?

Testing on OSX 10.7, php 5.3.6, phantomjs latest. User _www running the server has admin privileges, folder where I’m writing files were chmoded to 777.

How to&Answers:

You have several issues:

  1. phantomjs is started in the foreground, which means your php script stops/sleeps until phantomjs stops. Either start the phantomjs service, or run it in the background. See ” php execute a background process ” for an HowTo.
  2. The web server may probably not access the “graphical part” of your operating system, which means it cannot interact with your desktop. This is why the icon does not appear, but phantomjs should still start.