开发者

PHP CURL Parse multiple set-cookie headers using preg_match

开发者 https://www.devze.com 2023-03-14 02:30 出处:网络
I\'m using PHP/CURL to automate calls between 2 closely tied code igniter. Code igniter is returning two set-cookie headers, one for a secure cookie with the real session data, one for insecure conne

I'm using PHP/CURL to automate calls between 2 closely tied code igniter.

Code igniter is returning two set-cookie headers, one for a secure cookie with the real session data, one for insecure connections with an empty session...

Set-Cookie: overshare=a%3A0%3A%7B%7D; expires=Thu, 17-Jun-2010 05:09:32 GMT; path=/
Set-Cookie: overshare=BdHJPVt...STsCxnMBj; path=/; secure

I've been trying to parse the secure cookie (both sites are on the same domain so if I get updated session information via CURL, I should update the clients cookie as if they made the call directly)

I'm currently using the following to parse the cookie:

preg_match('/Set-Cookie: (.*)\b/', $Head, $Cookies);

which gives me in $Cookies:

Array
(
    [0] => Set-Cookie: overshare=a%3A0%3A%7B%7D; expires=Thu, 17-Jun-2010 05:09:32 GMT; path
    [1] => overshare=a%3A0%3A%7B%7D; expires=Thu, 17-Jun-2010 05:09:32 GMT; path
)

but this is only matching the first set-cookie header. My regex ski开发者_JAVA技巧lls are poor - how can I match the second header?


Assuming $Head is a single string containing all of the cookie headers, you're looking for preg_match_all(). preg_match() stops after finding the first match.

With preg_match_all(), matched entire strings will be in $Cookies[0]. Your subpattern matches will be in $Cookies[1].

$Head = <<<HEAD
Set-Cookie: overshare=a%3A0%3A%7B%7D; expires=Thu, 17-Jun-2010 05:09:32 GMT; path=/
Set-Cookie: overshare=BdHJPVt...STsCxnMBj; path=/; secure
HEAD;

preg_match_all('/Set-Cookie: (.*)\b/', $Head, $Cookies);

print_r($Cookies);

yields

Array
(
    [0] => Array
        (
            [0] => Set-Cookie: overshare=a%3A0%3A%7B%7D; expires=Thu, 17-Jun-2010 05:09:32 GMT; path
            [1] => Set-Cookie: overshare=BdHJPVt...STsCxnMBj; path=/; secure
        )

    [1] => Array
        (
            [0] => overshare=a%3A0%3A%7B%7D; expires=Thu, 17-Jun-2010 05:09:32 GMT; path
            [1] => overshare=BdHJPVt...STsCxnMBj; path=/; secure
        )

)

Also, your wildcard (.*) is greedy by default, so it may consume both strings together if the headers aren't on separate lines. If so, try (.*?) to make it ungreedy.

0

精彩评论

暂无评论...
验证码 换一张
取 消