Session and Cookie in PHP

PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?

When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are.

It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

So, Session variables hold information about one single user, and are available to all pages in one application.

Start a PHP Session

A session is started with the session_start() function. Session variables are set with the PHP global variable $_SESSION.

Now, let's create a new page called "demo_session.php". In this page, we start a new PHP session and set some session variables.

<?php
	// Start the session
	session_start();
?>
<!DOCTYPE html>
<html>
	<body>
		<?php
			// Set session variables
			$_SESSION["color"] = "white";
			$_SESSION["animal"] = "cat";
			echo "Session variables are set.";
		?>
	</body>
</html>

Get PHP Session Variable Values

Next, we create another page called session.php. From this page, we will access the session information we set on the first page demo_session.php.

Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page session_start().

Also notice that all session variable values are stored in the global $_SESSION variable.

<?php
	session_start();
?>
<!DOCTYPE html>
<html>
	<body>
		<?php
			// Echo session variables that were set on previous page
			echo "Favorite color is " . $_SESSION["color"] . ".<br>";
			echo "Favorite animal is " . $_SESSION["animal"] . ".";
		?>
	</body>
</html>

Another way to show all the session variable values for a user session is to run the following code.

<?php
	session_start();
?>
<!DOCTYPE html>
<html>
	<body>
		<?php
			print_r($_SESSION);
		?>
	</body>
</html>

Modify a PHP Session Variable

To change a session variable, just overwrite it.

<?php
	session_start();
?>
<!DOCTYPE html>
<html>
	<body>
		<?php
			// to change a session variable, just overwrite it
			$_SESSION["color"] = "black";
			print_r($_SESSION);
		?>
	</body>
</html>

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy().

<?php
	session_start();
?>
<!DOCTYPE html>
<html>
	<body>
		<?php
			// remove all session variables
			session_unset();
			// destroy the session
			session_destroy();
		?>
	</body>
</html>

PHP Cookies

A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.

They are typically used to keeping track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time.

A cookie can only be read from the domain that it has been issued from. Cookies are usually set in an HTTP header but JavaScript can also set a cookie directly on a browser.

Note: The setcookie() function must appear BEFORE the tag.

Setting Cookie In PHP

To set a cookie in PHP, the setcookie() function is used. The setcookie() function needs to be called prior to any output generated by the script otherwise the cookie will not be set.

Syntax:

setcookie (name, value, expire, path, domain, security);

Parameters:

The setcookie() function requires six arguments in general which are:

  1. Name: It is used to set the name of the cookie.
  2. Value: It is used to set the value of the cookie.
  3. Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
  4. Path: It is used to specify the path on the server for which the cookie will be available.
  5. Domain: It is used to specify the domain for which the cookie is available.
  6. Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.

Creating Cookie in PHP

The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30).

The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer). We then retrieve the value of the cookie "user" (using the global variable $_COOKIE).

We also use the isset() function to find out if the cookie is set.

<?php
	setcookie("Auction_Item", "Luxury Car", time()+2*24*60*60);
?> 

Only the name argument in the setcookie() function is mandatory. To skip an argument, the argument can be replaced by an empty string ("").


Modify a Cookie Value

To modify a cookie, just set (again) the cookie using the setcookie() function.

<?php
	setcookie("Auction_Item", "Luxury Bus", time()+2*24*60*60);
?>
<html>
	<body>
		<?php
			if(isset($_COOKIE["Auction_Item"])){
 				echo "Auction Item is a " . $_COOKIE["Auction_Item"];
			} else{
 				echo "No items for auction.";
			}
		?>
	</body>
</html>

Checking whether a Cookie is Set or Not

It is always advisable to check whether a cookie is set or not before accessing its value. Therefore to check whether a cookie is set or not, the PHP isset() function is used.

To check whether a cookie “Auction_Item” is set or not, the isset() function is executed as follows.

<?php
	if(isset($_COOKIE["Auction_Item"])){
 		echo "Auction Item is a " . $_COOKIE["Auction_Item"];
	} else{
 		echo "No items for auction.";
	}
?> 

Output:

Auction Item is a Luxury Car

Accessing PHP Cookie Values

For accessing a cookie value, the PHP $_COOKIE superglobal variable is used. It is an associative array that contains a record of all the cookies values sent by the browser in the current request.

The records are stored as a list where cookie name is used as the key. To access a cookie named “Auction_Item”, the following code can be executed.

<?php
	echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?> 

Output:

Auction Item is a Luxury Car

Deleting PHP Cookie

The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie() function is called by passing the cookie name and other arguments or empty strings but however this time, the expiration date is required to be set in the past.

To delete a cookie named “Auction_Item”, the following code can be executed.

<?php
	setcookie("Auction_Item", "", time()-60);
?>

Important Points for PHP Cookie

  • If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the session i.e. when the browser closes.
  • The same path, domain, and other arguments should be passed that were used to create the cookie in order to ensure that the correct cookie is deleted.