Skip to content

curl: exceptions in callbacks do not abort the request #16513

Open
@MagicalTux

Description

@MagicalTux

Description

A curl request may take time (sometimes an infinite amount of time) to respond. When an exception is thrown in a callback it is properly forwarded to the curl_exec, however in some cases such as server-sent events, the request may never end.

When an exception happens in a callback, the request should be aborted.

The following code:

<?php
$ch = curl_init('https://sse.fastlydemo.net/flights/stream');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) {
        echo "Noping away\n";
        throw new \Exception('nope!');
});

try {
        curl_exec($ch);
        if(curl_errno($ch)) throw new \Exception('CURL error: '.curl_error($ch));
} catch(\Throwable $e) {
        echo "Caught exception: $e\n";
}

Resulted in this output:

Noping away

(then nothing, the script freezes there)

But I expected this output instead:

Noping away
Caught exception: Exception: nope! in /tmp/test.php:9
Stack trace:
#0 [internal function]: {closure}()
#1 /tmp/test.php(14): curl_exec()
#2 {main}

PHP Version

PHP 8.2.20

Operating System

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions