Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get Cookies From Header String

Tags:

php

cookies

I have a string variable containing the header response. like this

This string is grabbed by sending a request through fsockopen() and fetching the header by

$nn= "\r\n";
    do {
        $header .= fgets ( $fp, 16384 );
    } while ( strpos ( $header, $nn . $nn ) === false );

output:

$header = "HTTP/1.0 200 OK Date: Tue, 13 Sep 2011 07:57:08 GMT Last-Modified: Tue, 13 Sep 2011 07:57:08 GMT 
Set-Cookie: EUID=face313a-dddd-11e0-a694-00000aab0f6c; 
expires=Mon, 08 Sep 2031 07:57:08 GMT; 
path=/; 
domain=.mysite.com; 
Set-Cookie: MIAMISESSION=face28e8-dddd-11e0-a694-00000aab0f6c:3493353428; 
path=/; 
domain=.mysite.com; 
Set-Cookie: USER_STATE_COOKIE=664d9ed4a110fa1deb0dc4cc2d7e76fa00a75a0b5c9b3fa8; 
path=/; 
domain=.mysite.com; 
Set-Cookie: MIAMIAUTH=f8d13d07cc4e8b0ef9904f5ce40367ce44c989661956ef1cd2804726b0dd5508db661a8f9582df19bc954c57d0f2c293760e4d5ddda88d556dbcfae8dd80a14c8378a2374eb5aeb636e8c4ca7849e48792f5588ad73b3d79ce55afb95660b5052d349082e88b29653d3df674e0fd328f75ad0edb5b63a434c0b7ce44b5c338a0676d6d6648b12e8e7f9570cf24b3ef7b5dfe647f2f36a62114ae5ef23b0a3f6ad15cabba99bf945243553a5329457337884d5671141f6cc438302813801fe2527ad29c1c4e76aedacded581bea2a1b6158b7d8ec3b09e2e6c9a87495f9e6d33188bdc5074d10564d30494e1b1f6af58ab96d11dd4817a0fc17619853792c8785; 
path=/; 
domain=.mysite.com; 
HttpOnly; 
Set-Cookie: SY_REMOTEACCESS=;
Content-Type: text/html Expires: Tue, 01 Jan 1980 04:00:00 GMT X-RE-Ref: 0 -77259901 X-Cache: MISS from 192.168.1.1 X-Cache-Lookup: MISS from 192.168.1.1 Via: 1.0 192.168.1.1 (squid) Connection: close";
";

now I want to get all cookies to an array

$cookie[1] = "EUID=face313a-dddd-11e0-a694-00000aab0f6c";
$cookie[2] = "MIAMISESSION=face28e8-dddd-11e0-a694-00000aab0f6c:3493353428";
...

how can I do that? Is that a regular expression job or is there a class or function to make this easier?

like image 403
John Avatar asked Sep 13 '11 08:09

John


1 Answers

Another way to do it:

    $headerCookies = explode('; ', getallheaders()['Cookie']);

    $cookies = array();

    foreach($headerCookies as $itm) {
        list($key, $val) = explode('=', $itm, 2);
        $cookies[$key] = $val;
    }
    
    print_r($cookies); // assoc array of all cookies
like image 72
Emmanuel Avatar answered Sep 17 '22 23:09

Emmanuel