Unit - 5 - PHP Cookie - Session
Unit - 5 - PHP Cookie - Session
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the
user.Cookie is created at server side and saved to client browser. Each time when client sends request to
the server, cookie is embedded with request. Such way, cookie can be received at the server side.A
cookie created by a user can only be visible to them. Other users cannot see its value. Most web
browsers have options for disabling cookies, third party cookies or both.
A simple example of cookies is when you open up a website and your username and password are
auto-filled. Cookies provided your login information to the website. Another example is when you go
online shopping on Amazon and find items that are still in your cart from your last purchasing spree.
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access
it by $_COOKIE superglobal variable.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
HERE,
Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
Cookie Value: Sonoo
PHP Delete Cookie
If you set the expiration date in past, cookie will be deleted.
File: cookie1.php
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body></html>
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {echo "Cookies are disabled.";}
?>
</body></html>
PHP Session
PHP session is used to store and pass information from one page to another temporarily (until user close
the website).
PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict between
multiple browsers.
PHP session_start() function is used to start the session. It starts a new or resumes existing session. It
returns existing session if session is created already. If session is not available, it creates and returns new
session.
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get
session variable values.
Example
File: session1.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Sachin";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body> </html>
File: session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body> </html>
Note: Both cookies and sessions must be started before any HTML tags have been sent to the browser.