cURL Callback Function

September 3, 2006 § 4 Comments

Usually we get cURL response from curl_exec(). But we have options to get the output using callback functions. We can set callback function for both header and body output. Here is an example:

//Init curl session
$ch = curl_init();
//Set URL
curl_setopt($ch, CURLOPT_URL, ‘http://www.php.net/’);
// Set callback function for headers
curl_setopt($ch, CURLOPT_HEADERFUNCTION, ‘read_header’);
// Set callback function for body
curl_setopt($ch, CURLOPT_WRITEFUNCTION, ‘read_body’);
//Execute curl
curl_exec($ch);

//close curl session
curl_close($ch);

//Callback function for header
function read_header($ch, $string)
{
$length = strlen($string);
echo “Header: $string
\n”;
return $length;
}

//Callback function for body
function read_body($ch, $string)
{
$length = strlen($string);
echo “Received $length bytes
\n”;
return $length;
}

This script demonstrates how you can set callback functions to receive the HTTP response as it comes through. It’s really easy to use but nice feature.

Enjoy PHPing !

$rupom

Advertisements

§ 4 Responses to cURL Callback Function

  • It is intersesting. But I have a small question: “How to cancel receiving data after call read_body 1-th?”. It means that “Request (GET|POST) with out response!”

  • Rupom says:

    If you want to cancel, just have a premature return in the read_body function. Thanks.

  • kudesnik says:

    How to send some args to callback function?
    For example:

    function getURL($url,$alias) {
    $ch = curl_init($url);
    // setting оptions
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, ‘read_body’);

    }

    function read_body($ch, $string, $alias) {
    switch ($alias) {
    case ‘1’ :
    // some stuff
    break;
    case ‘2’ :
    // some stuff
    break;

    }

    }

  • buzzknow says:

    if we want to use curl to download file, how to use this callback function to show progress to user?

    thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading cURL Callback Function at Rupom Here.

meta

%d bloggers like this: