JavaScript Tutorial

Sessions & Cookies

Sessions

Sessions are the super global variables which can be used across the multiple pages in a website. Session variables hold information about the user and help in carrying that information on various web pages of that website. Sessions create a temporary directory on the server which stores the variables and its values.

How to start php session

A session is started using session_start() method and the variables are set using $_SESSION variable.

Code example using session_start()

<?php
	session_start();
	$_SESSION['username'] = 'abcd';
	$_SESSION['userID'] = 1234;

	echo 'WELCOME '.$_SESSION['username'];
?>
<!--	OUTPUT:
	WELCOME abcd
-->

How to destroy php session

A session can be destroyed using session_unset() and session_destroy() method.

session_unset();	// remove all session variables
session_destroy();	// destroy the session

Cookies

A cookie is also used to check for an authenticated user. A cookie is a small file which is embedded to the user’s system. It is sent along with the page request by the user to the server. 

// syntax
setcookie(name, value, expiry, path, domain, secure, httponly);

// name parameter is required only
<?php
     $name = "user";
     $value = "John Doe";
     setcookie($name, $value, time() + (86400 * 30), "/");  // 86400 = 1 day
     if(!isset($_COOKIE[$name])) {
          echo $name . "  Cookie is not set!";
     } else{
            echo $name . " Cookie is set!<br>";
     }
?>
Go back to Previous Course