how to get the cookies from a php curl into a variable

后端 未结 8 746
囚心锁ツ
囚心锁ツ 2020-11-22 15:08

So some guy at some other company thought it would be awesome if instead of using soap or xml-rpc or rest or any other reasonable communication protocol he just embedded all

相关标签:
8条回答
  • 2020-11-22 15:51

    If you use CURLOPT_COOKIE_FILE and CURLOPT_COOKIE_JAR curl will read/write the cookies from/to a file. You can, after curl is done with it, read and/or modify it however you want.

    0 讨论(0)
  • 2020-11-22 16:02

    Although this question is quite old, and the accepted response is valid, I find it a bit unconfortable because the content of the HTTP response (HTML, XML, JSON, binary or whatever) becomes mixed with the headers.

    I've found a different alternative. CURL provides an option (CURLOPT_HEADERFUNCTION) to set a callback that will be called for each response header line. The function will receive the curl object and a string with the header line.

    You can use a code like this (adapted from TML response):

    $cookies = Array();
    $ch = curl_init('http://www.google.com/');
    // Ask for the callback.
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
    $result = curl_exec($ch);
    var_dump($cookies);
    
    function curlResponseHeaderCallback($ch, $headerLine) {
        global $cookies;
        if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
            $cookies[] = $cookie;
        return strlen($headerLine); // Needed by curl
    }
    

    This solution has the drawback of using a global variable, but I guess this is not an issue for short scripts. And you can always use static methods and attributes if curl is being wrapped into a class.

    0 讨论(0)
提交回复
热议问题