A cookie is a small file with a maximum size of 4KB. It is used to store user identification data.
Cookies are stored on the user’s local machine.
Each time a browser page is requested, the computer sends the cookie alongside for authentication. Cookies are only visible to the user who creates them.
Since HTTP is a stateless protocol, cookies are used to track the state of the application. They are also used to track websites visited by the user to store user preferences.
We can create a cookie as follows:
setcookie(name, value, expire, path, domain, secure, httponly);
nameparameter is required. The rest are optional.
The code snippet below shows how we can create a cookie in PHP:
The following cookie will expire in 30 days (86400s * 30).
<!DOCTYPE html> <?php $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day ?>
We can also retrieve the set cookie using the
cookie_name variable. It is done as follows:
<html> <body> <?php echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name]; ?> </body> </html>
Cookies are stored in the
_COOKIEvariable in PHP. Their value can be retrieved using the
cookie_namevariable, which acts as an identifier.
We can delete an existing cookie by changing its expiry date. We can set the expiry date to be before the current time.
setcookiefunction needs to be used again for this purpose.
The code snippet below shows how to delete the same cookie that we created before:
<?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600); ?>
A session variable stores information that can be used across web pages. Session variables are stored on the browser. Therefore, a session lasts till the webpage is closed.
A session begins by using the
session_start function. Each session variable is stored and retrieved from the global variable named
_SESSION. Session variable are then created as follows:
$_SESSION[identifier] = value;
The example below shows how one can create session variables in PHP:
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["name"] = "Educative"; $_SESSION["ID"] = "123"; ?> </body> </html>
The code snippet below shows how we can retrieve session variables in PHP:
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Echo session variables that were set on previous page echo "Company name is " . $_SESSION["name"] . ".<br>"; echo "Company ID is " . $_SESSION["ID"] . "."; ?> </body> </html>
A session can be using the
session_destroy functions in PHP.
session_unsetfunction removes all session variables.
session_destroyfunction destroys the session.
The example below shows how to destroy a session in PHP:
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // remove all session variables session_unset(); // destroy the session session_destroy(); ?> </body> </html>
View all Courses