Tag Archives: cookie

PHP

Shift cookies in current context

function  ShiftCookies($strHeaders)
{
	// Parse cookies
	$aCookies = ParseCookies($strHeaders);
	
	// Shift cookies in current context
	foreach ($aCookies as $cookie)
		@setrawcookie($cookie['name'], $cookie['value'], $cookie['expires'], $cookie['path'], $cookie['domain']);
}

ParseCookies is a function from post http://gik.firetrot.com/index.php/2011/08/03/parse-cookies-from-header/

PHP

Parse cookies from Header

If you want to get cookies from a header, use the following:

function ParseCookies($strHeaders)
{
	$result = array();
	
	if (!empty($strHeaders))
	{
		$aHeaders = explode("\n", trim($strHeaders));
		$strCookieStartLine = 'Set-Cookie:';
		
		foreach ($aHeaders as $line)
		{
			if (substr($line, 0, strlen($strCookieStartLine)) === $strCookieStartLine)
			{
				$aTmp = array();
				
				$aPairs = explode(';', trim(str_replace($strCookieStartLine, '', $line)));
				foreach ($aPairs as $pair)
				{
					$aKeyValues = explode('=', trim($pair), 2);
					if (count($aKeyValues) == 2)
					{
						switch ($aKeyValues[0])
						{
							case 'path':
							case 'domain':
								$aTmp[trim($aKeyValues[0])] = urldecode(trim($aKeyValues[1]));
								break;
							case 'expires':
								$aTmp[trim($aKeyValues[0])] = strtotime(urldecode(trim($aKeyValues[1])));
								break;
							default:
								$aTmp['name'] = trim($aKeyValues[0]);
								$aTmp['value'] = trim($aKeyValues[1]);
								break;
						}
					}
				}
				
				$result[] = $aTmp;
			}
		}
	}
	
	return $result;
}

This is author realization. Post a feedback if errors occurs.