PHP Cookies and Session

Cookies

  • In PHP, cookies is the small piece of information that the server embeds on the client’s computer. If users request the webpage from the browser, the cookie will also be sent with that. It is used to track user’s activity in the browser. A Cookie also has name and value.
  • A Cookie stores user-specific information such as username, last visit of a user, etc.
  • Variables can also be passed between pages by means of cookies.
  • A cookie is only visible to the user who created it and not by the other users.
  • The domain which has issued a cookie can only read it.
  • Sometimes the domain display elements from another website set their own cookies. This is called third party cookies.

Creating Cookies

In PHP, we can create cookie using setcookie() function.

Syntax for setcookie() function is:-

setcookie(name, value, [ expire_time ], [ path ], [ domain ], [ secure ], [ httponly ]);

In above piece of code

  • Name specify the name of the cookie and it is mandatory.
  • The value specifies the value associated with a cookie and it is mandatory.
  • The expire_time specifies the time when the cookie will expire. It is displayed in the second. And it is optional.
  • Path sets the cookie path on the server and it is optional.
  • Domain specifies the entire domain and limits access to its subdomain. It is optional.
  • Secure is optional and by default it is false. If it is true, the cookie is sent via https or else it is sent via HTTP. It is optional.
  • If Httponly is set to true then only client-side scripting language cannot access them. This is optional.

Example:-

<?php
	setcookie(" uname ", " TheCodeTutorial ", " time() + 120 ");
	echo "Cookie Expires after 2 minutes!!";
?>

The above example will set a cookie for variable uname and it will expire after 2 minutes.

Output:-

Cookie Expires after 2 minutes!!

Retrieving Cookies

  • In the PHP script, we can retrieve cookies using $_COOKIE.
  • $_COOKIE is a variable in PHP which contains the name and value of set cookies.
  • We can also use the isset() function to determine whether the cookie exists or not.

We can retrieve cookie which we have set in above example by following code

<?php
	if(isset($_COOKIE ['uname']))
	{
			echo $_COOKIE ['uname'];
	}
	else
	{
			echo "Cookie is not set"; 
	}
?>

In above example if cookie is set and not expired then it will output TheCodeTutorial else it will output Cookie is not set

Deleting Cookies

  • We can delete the cookie using the setcookie() function.
  • This is true that we can use setcookie() function with an empty value for cookie name or time that is already passed in expiry time to delete the cookie before it expires as PHP has not any specific function for unset or delete a cookie.

Example:

<?php
	setcookie(“ uname ”, “ TheCodeTutorial ”, “ time() - 360 ”);
?>

Above example will delete the cookie named uname

Sessions

  • In PHP, the session variable is a temporary variable that is created and stored at the server side to uniquely identify each user on website.
  • When we work with some software or application on a computer, we start it, do some modifications and then we close it and the computer knows who we are. It is like a session. But on the web there is one difficulty: the webserver doesn’t know who we are or what we do because the HTTP address doesn’t maintain state.
  • A session is created for each user when he or she logs on to the web application and it remains in existence until he or she logs out.
  • As we start the session, a unique identification number is generated for that user to uniquely identify the user.
  • Once the browser is closed, the session value is automatically deleted. If we want to store the values permanently, then we need to store it in a database.

Creating Session

In PHP, in order to create or access session variable we need to start the session at the starting of script using session_start() function.A session variable can be created using following syntax:

<?php
	$_SESSION['VariableName'] = value;
?>

The code below stores a session with two sessions variable employee id and name.

<?php 
	session_start(); 
	$_SESSION["Employee_Id"] = "01"; 
	$_SESSION["Employee_Name"] = "James"; 
?>

Accessing Session

Data can be easily accessed by calling session_start() and passing its key to the $_SESSION associative array.

Output:-

The Employee ID is : 01

The Employee Name is : James

Destroying Session

A session variable can be destroyed from the server using unset() function or using session_destroy() function.

Syntax for destroying the session is:

unset($_SESSION['SessionName']);

OR

session_destroy();

Example:-

<?php 
	session_start(); 
	if(isset($_SESSION["Employee_Name"]))
	{ 
		unset($_SESSION["Employee_Id"]); 
	}
?>