【问题标题】:PHP Curl output buffer not receiving responsePHP Curl输出缓冲区未收到响应
【发布时间】:2011-08-26 09:38:55
【问题描述】:

我有一个交易,file1.php curl 运行 file2.php。 file2.php 是一个长时间运行的文件,但它发送(或应该发送)一个响应回 file1.php 然后继续它的代码。我正在使用输出缓冲区尝试发送此数据,但问题是如果我“返回;”就在冲水之后; file1.php 收到响应很好,但是当我尝试保持 file2.php 运行时,file1.php 从未收到响应,我做错了什么?是否有其他方式我必须将响应发送回 file1.php?

// file1.php
    $url = "file2.php"

    $params = array('compurl'=>$compurl,'validatecode'=>$validatecode);

    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => true,     // return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "Mozilla", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_TIMEOUT        => 10,       // don't wait too long
        CURLOPT_POST           => true,     // Use Method POST (not GET)
        CURLOPT_POSTFIELDS     => http_build_query($params)
    );
    $ch = curl_init($url);

    curl_setopt_array( $ch, $options );
    $response = curl_exec($ch); 
    curl_close($ch);
    echo $response;

// file2.php
ob_start();
echo 'Running in the background.';

// get the size of the output
$size = ob_get_length();

header("HTTP/1.1 200 OK"); // I have tried without this
header("Date: " . date('D, j M Y G:i:s e')); // Tried without this
header("Server: Apache"); // Tried without this
header('Connection: close');
header('Content-Encoding: none');
header("Content-Length: $size");
header("Content-Type: text/html"); // Tried without this

// flush all output
ob_end_flush();
ob_flush();
flush();

// If I add return; here file1.php gets the response just fine
// But I need file2.php to keep processing stuff and if I remove the
// return; file1.php never gets a response.

【问题讨论】:

    标签: php curl buffer response


    【解决方案1】:

    在正常的 curl 传输中,在页面完成加载之前,您将无法获取数据,即。你的脚本完成了。如果您想使用部分数据,您应该查看 CURLOPT_WRITEFUNCTION 。这会创建一个回调,您可以在任何数据可用时使用该回调。

    【讨论】:

    • 但在另一个stackoverflow问题中表明这是可能的:stackoverflow.com/questions/2996088/…
    • 我试过 CURLOPT_WRITEFUNCTION 但它仍然没有读取任何响应.. 我如何循环以便它等待这个部分响应并且不退出脚本,但也不占用资源?
    • Curl 不是浏览器。您的浏览器可以显示部分数据,但 curl 只会在页面完成后返回。坦率地说,除非您使用多线程,否则我无法想象函数如何返回部分数据。要使用部分数据,您需要一个 CURLOPT_WRITEFUNCTION 提供的回调。
    • 如果您需要这种行为,即同时获取和处理,最好使用多线程语言编写应用程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    相关资源
    最近更新 更多