Location: PHPKode > scripts > HTTP Cookie > httpcookie.php
<?php
/**
 * HTTPCookie
 * This class can be used to manipulate cookies from request header values.
 * It can parse HTTP request cookie header values and perform several types of operations like checking whether cookie has expired given its expiry date, rebuild cookies request header from an array of cookies, save or load the list of cookies from a file.
 *
 * @package httpcookie
 * @access public
 * @author WindyLea (hide@address.com, 2011)
 * @version 0.2.2
 */
class httpcookie
{
	/**
	* Check if a cookie is expired or not
	*
	* @access public
	* @param string $time The value of the "expires" key presented in the "Set-Cookie" header
	* @return bool *true* if the cookie is expired or malfunctioned ( not in the format "Wdy, DD-Mon-YYYY HH:MM:SS GMT" )
	*/

	function is_expired_cookie($time)
	{
		if(empty($time))
			return false;

		$time_conv = strtotime($time);
		$time_now = time();

		if(is_int($time_conv) && $time_conv >= $time_now)
			return false;
		return true;
	}

	/**
	* Parse value for a specified header from an array of HTTP headers, can be used for any type of header, not just "Set-Cookie"
	*
	* @access public
	* @param array $headers Contains HTTP headers to be parsed
	* @param string $header The header whose value will be returned
	* @param bool $overwrite Default is *false*
	* @return false|string|array *false* if $headers/$header is empty or no value found; otherwise, array if $overwrite is *false* and string if $overwrite is *true*
	*/

	function header($headers, $header, $overwrite = false) {
		if(empty($header) || !is_array($headers))
			return false;

		$return = false;

		foreach($headers as $e)
		{
			if(!preg_match("/^".$header.":/i", $e))
				continue;

			$e = trim(preg_replace("/^".$header.":/i", "", trim($e)));

			if(empty($e))
				continue;

			if($overwrite === true)
				$return = $e;
			else
				$return[] = $e;
		}

		return $return;
	}

	/**
	* Parse cookies from HTTP headers
	*
	* @access public
	* @param array $headers Contains HTTP headers to be parsed for "Set-Cookie" headers
	* @param string $url The original URL returned the HTTP headers ( $headers )
	* @param array $cookies Existing array which was returned from this class ( specify to update it ); default is an empty array
	* @return false|array *false* if $headers/$url is empty or no Cookie found; array on success
	*/

	function parse($headers, $url, $cookies = array())
	{
		if(empty($url) || !is_array($headers))
			return false;

		$headers = httpcookie::header($headers, "Set-Cookie");

		if($headers === false)
			return false;

		$output = parse_url(trim($url));

		if(empty($output["path"]))
			$output["path"] = "/";

		foreach($headers as $header)
		{
			$elements = explode(";", $header);
			$cookie = array(
				"secure" => 0, 
				"httponly" => 0
			);

			foreach($elements as $element)
			{
				list($name, $content) = explode("=", trim($element), 2);
				$name = trim($name);

				if(empty($name))
					continue;

				switch($name) 
				{
					case "domain":
					case "path":
					case "comment":
					case "expires":
					case "max-age":
						$cookie[$name] = trim($content);
						break;
					case "secure":
					case "httponly":
						$cookie[$name] = 1;
						break;
					default:
						if(!empty($content)) 
							$cookie_name = $name;

						$cookie[$name] = trim($content);
						break;
				}
			}

			if(empty($cookie["domain"])) 
				$cookie["domain"] = $output["host"];

			if(empty($cookie["path"])) 
				$cookie["path"] = $output["path"];

			$cookies[$cookie["domain"]][$cookie["path"]][$cookie_name] = $cookie;
		}

		return $cookies;
	}

	/**
	* Rebuild cookies
	*
	* @access public
	* @param array $cookies Existing array which was returned from this class
	* @param string $url The target URL to build cookies for
	* @param bool $expires Force selecting not expired cookies only, default is *false*
	* @return false|string *false* if $cookies/$url is empty; string on success
	*/

	function build($cookies, $url, $expires = false) 
	{
		if(empty($url) || !is_array($cookies)) 
			return false;

		$output = parse_url(trim($url));

		if(empty($output["path"])) 
			$output["path"] = "/";

		$host_length = strlen($output["host"]);
		$path_length = strlen($output["path"]);
		$scheme = $output["scheme"];
		$return = null;

		foreach($cookies as $domain => $contents) 
		{
			$result = $host_length - strlen($domain);
			if($domain == $output["host"] || $result > 0 || (".".$output["host"] == $domain)) 
			{
				foreach($contents as $path => $cookie) 
				{
					if($path_length >= strlen($path) && substr($output["path"], 0, strlen($path)) == $path) 
					{
						foreach($cookie as $name => $value) 
						{
							if($expires && httpcookie::is_expired_cookie($value["expires"])) 
								continue;

							if($scheme == "http" && $value["secure"] != 0 && $value["httponly"] != 0)
								continue;

							$return .= $name . "=" . $value[$name] . "; ";
						}
					}
				}
			}
		}

		return trim($return);
	}

	/**
	* Save cookies for later use by using serialize() function
	*
	* @access public
	* @param array $cookies Existing array which was returned from this class
	* @param string $filename The file for the cookies to be written to; default is null
	* @return bool|string
	*/

	function save($cookies, $filename = null) 
	{
		$cookie = serialize($cookies);
		if(empty($filename) || !is_string($filename)) 
			return $cookie;

		if(is_writable($filename) || !file_exists($filename)) 
		{
			if($handle = fopen($filename, "w+")) 
			{
				fwrite($handle, $cookie);
				fclose($handle);
				return true;
			}
		}

		return false;
	}

	/**
	* Load cookies from saved cookies
	*
	* @access public
	* @param string $string
	* @param bool $filename
	* @return array|false Array on success
	* @return array|false Array on success
	*/

	function load($string, $filename = false) 
	{
		if(!$filename) 
		{
			$cookies = unserialize($string);
			return $cookies;
		}

		if(is_readable($string)) 
		{

			if($handle = fopen($string, "r")) 
			{
				$filesize = filesize($string);

				if($filesize > 0) 
				{
					$contents = fread($handle, $filesize);
					fclose($handle);
					$cookies = unserialize($contents);
					return $cookies;
				}
			}
		}

		return false;
	}
}

if(!function_exists("http_build_cookies")) 
{
	function http_build_cookies() 
	{
		$args = func_get_args();
		return call_user_func_array(array("httpcookie", "build"), $args);
	}
}

if(!function_exists("http_parse_cookies")) 
{
	function http_parse_cookies() 
	{
		$args = func_get_args();
		return call_user_func_array(array("httpcookie", "parse"), $args);
	}
}

if(!function_exists("http_save_cookies")) 
{
	function http_save_cookies() 
	{
		$args = func_get_args();
		return call_user_func_array(array("httpcookie", "save"), $args);
	}
}

if(!function_exists("http_load_cookies")) 
{
	function http_load_cookies() 
	{
		$args = func_get_args();
		return call_user_func_array(array("httpcookie", "load"), $args);
	}
}
?>
Return current item: HTTP Cookie