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

后端 未结 8 827
囚心锁ツ
囚心锁ツ 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:44

    The accepted answer seems like it will search through the entire response message. This could give you false matches for cookie headers if the word "Set-Cookie" is at the beginning of a line. While it should be fine in most cases. The safer way might be to read through the message from the beginning until the first empty line which indicates the end of the message headers. This is just an alternate solution that should look for the first blank line and then use preg_grep on those lines only to find "Set-Cookie".

        curl_setopt($ch, CURLOPT_HEADER, 1);
        //Return everything
        $res = curl_exec($ch);
        //Split into lines
        $lines = explode("\n", $res);
        $headers = array();
        $body = "";
        foreach($lines as $num => $line){
            $l = str_replace("\r", "", $line);
            //Empty line indicates the start of the message body and end of headers
            if(trim($l) == ""){
                $headers = array_slice($lines, 0, $num);
                $body = $lines[$num + 1];
                //Pull only cookies out of the headers
                $cookies = preg_grep('/^Set-Cookie:/', $headers);
                break;
            }
        }
    

提交回复
热议问题