PHP file_get_contents发送大POST

时间:2014-04-17 12:46:09

标签: php curl file-get-contents

我有以下方法发送file_get_contents个请求:

protected function query($page, $post, $timeout = false, $debug = false, $enableWarnings = true) {
    $this->correctHostIfNeeded(self::HTTP_CONNECTION_TYPE);
    $page = $this->host . (substr($page, 0, 1) == '?' ? '' : '?') . $page;
    $opts = array('http' => array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
    ));
    if (!empty($post)) {
        $postdata = http_build_query($post);
        $opts['http']['content'] = $postdata;
    }
    if ($timeout > 0)
        $opts['http']['timeout'] = $timeout;
    $context = stream_context_create($opts);
    $result = $enableWarnings ? file_get_contents($page, false, $context) : @file_get_contents($page, false, $context);
    return $result;
}

它通常工作正常,优于curl版本(无论后期数据如何,它偶尔也无法正常执行)。不幸的是,如果我发送了很大的POST file_get_contents(例如带有100k元素的数组),它就会失败。有时目标服务器会保存部分数据,但它永远不会得到所有数据。

我知道服务器之间的互联网连接不是问题(两台服务器都在我自己的数据中心,两者之间的速度稳定在100Mb左右)。此外,两个服务器上的代码本身似乎都很好,因为数据较小,它工作正常,如果我更改为curl正确接收大包(不幸的是它有时会失败,我读到它并不奇怪卷曲的行为。)

2 个答案:

答案 0 :(得分:1)

增加页面的执行时间,将其写在顶部 -

ini_set('max_execution_time', 300); 

答案 1 :(得分:0)

尝试按部分读取文件,然后合并结果。在file_get_context中,您可以指定offset和max_length参数。