PHP CURLOPT_WRITEFUNCTION將頭部資訊傳回正文中
P粉799885311
P粉799885311 2024-03-19 19:20:53
0
1
464

當我包含 curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curl_write_flush') 時,我將標頭插入到 $body 中。但如果沒有 CURLOPT_WRITEFUNCTION 一切正常。我該怎麼做才能阻止標頭插入 $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

全部回覆(1)
P粉262113569

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

要嘛去掉 curl_setopt($ch, CURLOPT_HEADER, 1);,否則您必須自己從回呼資料解析出標頭。

您也可以使用CURLOPT_HEADERFUNCTION,如本答案所示:

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

#
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!