2 mins read

Handling Sessions and Cookies in PHP

When building websites, sometimes you need to remember information about a user. This is where sessions and cookies come in handy. Let’s explore how to use them in PHP.

 

What is a Session?

 

A session is a way to store information (in variables) to be used across multiple pages. Unlike cookies, the information is not stored on the user’s computer. Sessions are safer because the data is stored on the server.

 

Starting a Session

 

To start a session in PHP, you use the `session_start()` function. This function must be called at the beginning of your PHP script before any HTML or other output.

<?php
session_start();
?>


Storing Session Data

 

Once a session is started, you can store data in it like this:


<?php
$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = 'john@example.com';
?>


Accessing Session Data

 

To access session data, you simply refer to the `$_SESSION` superglobal array:

<?php
echo $_SESSION['username']; // Outputs: JohnDoe
echo $_SESSION['email']; // Outputs: john@example.com
?>


Ending a Session

 

To end a session and clear all session data, use the following:

<?php
session_start();
session_unset();
session_destroy();
?>


What is a Cookie?

 

 

A cookie is a small file stored on the user’s computer. Cookies can remember information about the user, like login details or preferences, even after they leave the website.

 

Setting a Cookie

 

To set a cookie in PHP, you use the `setcookie()` function. This function must be called before any HTML or other output.


<?php
setcookie('username', 'JohnDoe', time() + (86400 * 30), "/"); // 86400 = 1 day
?>

This sets a cookie named “username” with the value “JohnDoe” that expires in 30 days.

 

Accessing a Cookie

 

To access a cookie, you use the `$_COOKIE` superglobal array:

<?php
if (isset($_COOKIE['username'])) {
echo 'Username is ' . $_COOKIE['username']; // Outputs: Username is JohnDoe
} else {
echo 'Cookie not set';
}
?>


Deleting a Cookie

 

To delete a cookie, you set its expiration date to a past time:


<?php
setcookie('username', '', time() - 3600, "/");
?>

When to Use Sessions vs. Cookies

 

– Use Sessions when:
– You need to store sensitive information.
– The data should not be accessible by the user directly.
– The data only needs to be available while the user is on your site.

– Use Cookies when:
– You need to remember information across visits.
– The data is not sensitive.
– You want the user to be able to control or view the data.

 

 

Sessions and cookies are essential tools for managing user information in PHP. Sessions are great for temporary, secure storage on the server, while cookies are useful for storing information on the user’s computer for future visits. Understanding how to use them effectively can make your website more dynamic and user-friendly.

 

Leave a Reply

Your email address will not be published. Required fields are marked *