Search code examples
phpcurlphp-curl

PHP cURL: Reset Callback (CURLOPT_HEADERFUNCTION)


I have a code similar to the following:

$ch = curl_init();
// ...
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header_line) {
    // process $header_line...
    return strlen($header_line); // needed by curl
});
// ...
curl_exec($ch);

After that code I'd like to keep using $ch to re-use the connection, but I don't need the custom CURLOPT_HEADERFUNCTION callback anymore. How can I reset it? I tried setting it to null but it didn't work.


Solution

  • Set the common options in an array and reset options between executions:

    $common_options = [
        CURLOPT_XXX => 'something'
        // ...
    ];
    $ch = curl_init();
    
    // First call: common + specific options
    curl_setopt_array($ch, $common_options);
    curl_setopt($ch, CURLOPT_FOO, 'something else');
    
    curl_exec($ch);
    
    // Second call: common options only
    curl_reset($ch);
    curl_setopt_array($ch, $common_options);
    
    curl_exec($ch);