PHP CURLOPT_WRITEFUNCTION returns header information to the body
P粉799885311
P粉799885311 2024-03-19 19:20:53
0
1
463

When I include curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curl_write_flush'), I insert the header into the $body. But without CURLOPT_WRITEFUNCTION everything works fine. What can I do to prevent the header from inserting $body?

<?php

    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, "https://stackoverflow.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    function curl_write_flush($curl_handle, $chunk) {
        echo $chunk;
        ob_flush();
        flush();
        return strlen($chunk);
    }
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curl_write_flush'); // WORKS WITHOUT

    $response = curl_exec($ch);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

    curl_close($ch);

    $headers = substr($response, 0, $header_size);
    $body = substr($response, $header_size);

    die($body);

?>

P粉799885311
P粉799885311

reply all(1)
P粉262113569

https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html

Either get rid of curl_setopt($ch, CURLOPT_HEADER, 1);, or you must parse the headers from the callback data yourself.

You can also use CURLOPT_HEADERFUNCTION as shown in this answer:

https://stackoverflow.com/a/41135574/1064767

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!