PHP fopen()和php://内存不能正常工作(数据丢失)

时间:2014-12-18 15:31:44

标签: php curl fopen php-stream-wrappers

我目前正在尝试将使用fopen()的类与php://memory流集成以捕获Curl标头。有一些更好的方法来捕获Curl标题,但是我现在没有足够的时间编写自己的类。

问题是没有捕获标头信息。代码如下:

    $response_headers_fh = fopen('php://memory', 'wb+');

    $ch->setOpt(CURLOPT_WRITEHEADER, $response_headers_fh);

    $ch->raw_response = curl_exec($ch->curl);

    rewind($response_headers_fh);
    $ch->raw_response_headers = stream_get_contents($response_headers_fh);
    fclose($response_headers_fh);

此时,在Curl请求之后,$ch->raw_response_headers属性为空。但是,如果我指定文件路径:

    $response_headers_fh = fopen('/tmp/random_string', 'wb+');

    $ch->setOpt(CURLOPT_WRITEHEADER, $response_headers_fh);

$ch->raw_response_headers属性设置正确...

我们的PHP版本是:

$ php -v
PHP 5.3.3 (cli) (built: Sep 10 2014 07:51:23)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
    with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans

有点难过......

1 个答案:

答案 0 :(得分:1)

卷曲无法写入php://memory流是合理的。到目前为止,有一个旧的bug report似乎尚未解决。但您可以使用CURLOPT_HEADERFUNCTION - 选项来捕获标题:

function MyHeaderFunction($ch, $header)
{
    echo 'Header = ' . $header;
    return strlen($header);
}

$ch->setopt(CURLOPT_HEADERFUNCTION, 'MyHeaderFunction');

curl_exec($ch->curl);