Friday, September 6, 2019

Session & Cookies

Session & Cookies

As we know that HTTP is a stateless protocol. If we want to track any user information on any website on browser. In that case, we have two options: Session and Cookies.

A session is a global variable, which is stored on web server. Here, we can store unlimited amount of data. Here we can create more than one session and every sessions keeps a unique id, which is used to get stored values. When we close browser, it will remove session information. Suppose, we are going to purchase any product from shopping website. When we search that product on shopping site and click on Add To Cart. It stores product information in session.
For store any data in session, we have to start session by session_start(). After that, we stores values in PHP global variable $_SESSION.

For Example,

$_SESSION['name'] = 'Kamal';
$_SESSION['email'] = '';
$_SESSION['age'] = '23';

For display session variable values, we have to start session and use PHP global variable.

For Example,
echo "Name is: ".$_SESSION['name']. "<br/>";
echo "Email is: ".$_SESSION['email']. "<br/>";
echo "Age is: ".$_SESSION['age']. "<br/>";

For destroy session variable, we use session_destroy() function to destroy all session variable.

For Example,
session_destroy(); //If you want to destroy all session variable.

unset($_SESSION['name']); //If you want to remove a single variable from session.

It is also used to store users data, but stores on client computer. Here, we can store limited amount of data. We can store only 4KB data in cookies. Cookies keeps expiration time for cookies variable. Suppose, when we login gmail account with email and password then it display all our emails. If we close browser and again want to login with gmail, then it opens our all emails without asking email and password.
For create cookies,

setcookie(cookies_name, cookies_value, expiry_time, cookies_stored_path, domain, secure, httponly);

For Example:
setcookie('name', 'Kamal', time()+120, '/'); //It will expire 120 seconds.

For get cookies value, we use php global variable $_COOKIE.

For Example,
echo "Your cookies value is: ". $_COOKIE['name'];

Answer is:
Your cookies value is: Kamal

For destroy cookies, we set any past date in place of expiration date.

For Example,
setcookie('name', '', time()-3600);

No comments:

Post a Comment

Copyright © 2019 Tech Location BD. All Right Reserved