Alex
Alex

Reputation: 11

Closing curl handle in header/write callback

Is it okay to close curl handler inside a CURLOPT_HEADERFUNCTION or CURLOPT_WRITEFUNCTION callback? e.g.

            curl_setopt_array($ch, array(
                            CURLOPT_HEADERFUNCTION => array($this, 'callbackWriteHeader'),
                            CURLOPT_WRITEFUNCTION  => array($this, 'callbackWriteBody'),
                ...
            protected function callbackWriteHeader($ch, $string) {
                        if (...<check headers here...) {
                                    curl_close($ch);
                        }

use case for this: i don't want to download large files and want to avoid extra HEAD request just to learn filesize (because 99% of the files I download are small).

Upvotes: 1

Views: 836

Answers (2)

Mikhail Gerasimov
Mikhail Gerasimov

Reputation: 39516

Better way for you would be:

curl_setopt($ch, CURLOPT_NOBODY, true);

Answering about closing cutl in header callback:

Return the number of bytes actually written or return -1 to signal error to the library (it will cause it to abort the transfer with a CURLE_WRITE_ERROR return code).

http://curl.haxx.se/libcurl/php/examples/callbacks.html

Upvotes: 1

Riimu
Riimu

Reputation: 1437

That approach seems a bit sketchy at best and the behavior may be undefined. I have not tried whether it works or not, but personally I would approach the issue by throwing an exception instead. That seems like a more standard way to handle problems within functions and to return to previous state.

The exception handler outside the cURL call can then handle closing the handle itself.

Upvotes: 1

Related Questions