PHP fopen() and php://memory not working as expected (data-loss)

823 views Asked by At

I am currently trying to integrate a Class that uses fopen() with a php://memory stream to capture Curl headers. There are invariably better ways to capture the Curl headers, but I am not with enough time to write my own class at this moment.

The issue is that no header information is captured. The code is as follows:

    $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);

At this point, after the Curl request, the $ch->raw_response_headers property is empty. However, if I specify a file-path:

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

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

The $ch->raw_response_headers property is set properly...

Our PHP version is:

$ 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

Kind of stumped...

1

There are 1 answers

0
huysentruitw On BEST ANSWER

It is plausible that curl isn't able to write to the php://memory stream. There is an old bug report that seems unresolved until now. But you can use the CURLOPT_HEADERFUNCTION-option to capture the header instead:

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

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

curl_exec($ch->curl);