0
0
PHPprogramming~5 mins

Session vs cookie decision in PHP

Choose your learning style9 modes available
Introduction

Sessions and cookies help websites remember you. Choosing between them depends on what you want to save and how safe it should be.

Remembering a user login safely during a visit.
Saving small preferences like language or theme across visits.
Tracking items in a shopping cart temporarily.
Storing sensitive data that should not be visible to users.
Keeping data available even after the browser is closed.
Syntax
PHP
<?php
// Start a session
session_start();

// Set a session variable
$_SESSION['key'] = 'value';

// Set a cookie
setcookie('key', 'value', time() + 3600); // expires in 1 hour
?>

Sessions store data on the server and use a cookie to link the user.

Cookies store data on the user's browser and can last longer.

Examples
This saves the username in a session for the current visit.
PHP
<?php
session_start();
$_SESSION['username'] = 'Alice';
?>
This saves the user's theme choice in a cookie for 1 day.
PHP
<?php
setcookie('theme', 'dark', time() + 86400); // 1 day
?>
Sample Program

This program chooses between session and cookie based on a simple condition. It shows how to set each and explains the difference in duration.

PHP
<?php
// Start session
session_start();

// Decide to use session or cookie
$userPrefersRemember = true; // example decision

if ($userPrefersRemember) {
    // Use cookie to remember user for 7 days
    setcookie('user', 'Bob', time() + 7 * 24 * 3600);
    echo "Cookie set to remember user for 7 days.";
} else {
    // Use session to remember user only during visit
    $_SESSION['user'] = 'Bob';
    echo "Session set to remember user during this visit.";
}
?>
OutputSuccess
Important Notes

Sessions are safer for sensitive data because data is stored on the server.

Cookies can be seen and changed by users, so avoid storing secrets there.

Sessions expire when the browser closes or after inactivity, cookies can last longer.

Summary

Use sessions to store sensitive or temporary data during a visit.

Use cookies to save small, non-sensitive data across visits.

Decide based on how long you want to remember and how safe the data should be.