【问题标题】:How to do a http request with callback on response from php?如何在来自php的响应中回调一个http请求?
【发布时间】:2012-05-25 02:02:23
【问题描述】:

我需要编写一个 php 脚本,它将向我的 PhantomJs 服务器发出 POST 请求,并在收到响应后调用一些回调函数。

假设这是我的 phantomjs 服务器:

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();
});

因此,我需要从我的 php 脚本中向http://localhost:8080 发出请求,当 phantomjs 完成计算并发送响应时,触发回调函数。 我找到了这个话题:How do I make an asynchronous GET request in PHP?。这里有什么用处吗?我正在考虑这种 curl 方法,但不确定如何让所有这些一起运行,因为我是一个完全的 php 初学者:How do I make an asynchronous GET request in PHP?

【问题讨论】:

    标签: php curl callback xmlhttprequest phantomjs


    【解决方案1】:

    您可以使用cURLhttp://www.php.net/manual/en/book.curl.php 这是手册。没什么复杂的。

    <?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; 
        } 
    ?>
    

    这是来自示例的代码,适合您的需求。

    【讨论】:

    • 这个基于回调的意义是什么? OP 规定解决方案应该是异步的。
    猜你喜欢
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多