Handling Sessions and Cookies

What is a Cookie?

A cookie is a small data file stored by a web server on the user’s browser. Each time the user revisits the site, the browser sends the cookie back to the server. This allows websites to remember important user data, such as login status, cart items, or previously entered form values.

Cookies make the browsing experience smoother by avoiding repeated inputs. Moreover, they help websites offer personalised content based on past interactions.

Creating Cookies in PHP

PHP provides the setcookie() function to create cookies.

Syntax:

setcookie(name, value, expire, path, domain, secure, httponly);

Out of all the parameters, only name is required. The rest are optional but help define the cookie’s behavior.

Example: Creating and Retrieving a Cookie

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Output:
Cookie ‘user’ is set!
Value is: John Doe

Note: Always place setcookie() before any HTML output; otherwise, it won’t work. After setting a cookie, reloading the page is often necessary to view the stored value.

Modifying a Cookie Value

To update a cookie, simply call setcookie() again with the same name but a new value.

Example:

<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>

Output:
The cookie value changes, although you may need to refresh the page to view the new value.

Deleting a Cookie

Deleting a cookie requires setting its expiry time to a past value. PHP then considers it expired.

Example:

<?php
setcookie("user", "", time() - 3600);
?>

Output:
The ‘user’ cookie has been removed.

Checking if Cookies are Enabled

You can determine whether cookies are enabled by trying to set one and then checking if it appears in the $_COOKIE array.

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>

Output:
Cookies are enabled.


What is a Session?

A session enables data to persist across multiple web pages by storing it on the server. Unlike cookies, session data is not visible to users. Therefore, it offers more security and privacy.

Sessions are perfect for storing sensitive information like usernames, preferences, or cart items during a user’s visit.

Starting a PHP Session

To begin working with sessions, you must start one using session_start(). This function should be placed before any HTML content is rendered.

Example: Creating Session Variables

<?php
session_start();
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

Output:
Session variables are set.

Accessing Session Variables

Session values are stored in the $_SESSION array and can be accessed on any page after starting the session.

Example: Access Session Data

<?php
session_start();
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

Output:
Favorite color is green.
Favorite animal is cat.

To see all session data, you can use:

<?php
session_start();
print_r($_SESSION);
?>

Output:
Array ( [favcolor] => green [favanimal] => cat )

How Does a Session Work?

Whenever session_start() is called, PHP generates a unique session ID. This ID is sent to the user’s browser, typically stored in a cookie. On every page request, PHP uses this ID to fetch the corresponding session data from the server.

This entire process happens behind the scenes, making it seamless for developers and users alike.

Modifying Session Variables

To change any session value, just reassign it using the same key.

Example:

<?php
session_start();
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

Output:
Array ( [favcolor] => yellow [favanimal] => cat )

Destroying a Session

If you wish to completely end a session and remove all stored variables, you need to call both session_unset() and session_destroy().

Example:

<?php
session_start();
session_unset(); 
session_destroy();
echo "All session variables are now removed, and the session is destroyed.";
?>

Output:
All session variables are now removed, and the session is destroyed.

Â