Home > Software engineering >  PHP CURLOPT_WRITEFUNCTION returns headers in body
PHP CURLOPT_WRITEFUNCTION returns headers in body

Time:05-27

When i include curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curl_write_flush'), i get headers inserted into the $body. But without CURLOPT_WRITEFUNCTION everything works fine. What can i do to stop the headers been inserted into the $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);

?>

CodePudding user response:

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

If CURLOPT_HEADER is enabled, which makes header data get passed to the write callback, you can get up to CURL_MAX_HTTP_HEADER bytes of header data passed into it. This usually means 100K.

Either get rid of curl_setopt($ch, CURLOPT_HEADER, 1); or you'll have to parse out the headers from the callback data yourself.

You may also be able to use CURLOPT_HEADERFUNCTION as in this answer:

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

  • Related