PHP MySQL tutorial

Cookies in PHP

Cookies and sessions are the two major ways in which browser stores user information. HTTP is a stateless protocol and every request sent to the browser is a new request. So there is a need for a mechanism which help browsers track record of the visiting user and then serve them with the related pages.

For instance when you first time visit a site, you are presented with login page where you login to the website. Next time when you click a link on the website, you are initiating a new HTTP request, how does a browser know that you are already logged in? The browser does this with the help of cookies and sessions.

Cookies are simple. When you visit a page, server saves client information on the client’s system. When the client again accesses the server, the cookie information is sent to the server with the request and server serves the related page to the user. Creating cookies is extremely simple in PHP. Have a look at the following example.

<?php
	$cook_name = "car";
	$cook_value = "Honda";
	setcookie($cook_name, $cook_value, time() + (86400 * 7), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
	if(!isset($_COOKIE[$cook_name])) {
		echo "Your cookie '" . $cook_name . "' is not available";
	} else {
		echo "Your cookie '" . $cook_name . "' is available!<br>";
		echo "Value for your cookie is: " . $_COOKIE[$cook_name];
	}
?>
</body>
</html>

Download the code
Run the code

To set the cookie PHP contains a setcookie function which takes minimum of four arguments. The first argument is the name of the cookie, then value of the cookie, the time for which cookie will stay on client’s computer and the path. It is pertinent to mention that cookies must be created before any HTML tag on the page. The isset function can be used to check if cookie exists. The value of the cookie can be accessed by passing cookie name to the associative array $_COOKIE. Remember that time is in seconds. One day contains 86400 seconds, so to set a cookie for one week you have to multiply this value to 7.

Deleting a Cookie

Deleting a cookie is also very simple. You have to use the setcookie function but set the time to some value in the past. Have a look at the following example.

<?php
	setcookie("car", "", time() - 3600);
?>
<html>
<body>

<?php
	echo "Cookie 'car is removed from your system.'.";
?>

Download the code
Run the code

<<< Functions in PHPSessions in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .