1

I need to write a php script, that will do a POST request to my PhantomJs server, and call some callback function after receiving response.

Let's say this is my phantomjs server :

var server, service;

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

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

    //do_something_heavy_with_request_data_here

    response.statusCode = 200;
    response.write("{status: success, data: data}");
    response.close();
});

So from my php script I need to do a request to http://localhost:8080 and when phantomjs finishes it's calculations and sends response, fire a callback function. I've found this topic : How do I make an asynchronous GET request in PHP? . Anything useful here ? I was thinking about this curl approach, but not sure how to get all of this running together since I'm a total php beginner : How do I make an asynchronous GET request in PHP? .

Community
  • 1
  • 1
mike_hornbeck
  • 1,612
  • 3
  • 30
  • 51

1 Answers1

0

You can use cURL. http://www.php.net/manual/en/book.curl.php Here's manual. there's nothing complicated.

<?php 

/** 
 * Send a POST requst using cURL 
 * @param string $url to request 
 * @param array $post values to send 
 * @param array $options for cURL 
 * @return string 
 */ 
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 => 4, 
        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); 
    return $result; 
    } 
?>

This is a code from example, that fits your needs.

Leri
  • 12,367
  • 7
  • 43
  • 60
  • 5
    In what sense is this callback-based? The OP stipulates the solution should be asynchronous. – 1owk3y Oct 02 '18 at 02:07