0
0
PhpHow-ToBeginner · 3 min read

How to Set Session Variable in PHP: Simple Guide

To set a session variable in PHP, first start the session using session_start(). Then assign a value to a session variable using the $_SESSION superglobal array, like $_SESSION['key'] = 'value';.
📐

Syntax

To set a session variable in PHP, you must first start the session with session_start(). Then you can assign values to the $_SESSION array using a key and value.

  • session_start(); - Initializes the session or resumes the current one.
  • $_SESSION['key'] = 'value'; - Sets a session variable with the name 'key' and assigns it the value 'value'.
php
<?php
session_start();
$_SESSION['username'] = 'Alice';
?>
💻

Example

This example shows how to start a session, set a session variable, and then display it on the page.

php
<?php
session_start();
$_SESSION['favorite_color'] = 'blue';
echo 'Your favorite color is ' . $_SESSION['favorite_color'] . '.';
?>
Output
Your favorite color is blue.
⚠️

Common Pitfalls

Common mistakes when setting session variables include:

  • Not calling session_start() before accessing $_SESSION.
  • Trying to set session variables after outputting HTML, which causes headers to be sent and session start to fail.
  • Forgetting that session variables persist across pages until the session ends or variables are unset.
php
<?php
// Wrong way: session_start() missing
// $_SESSION['user'] = 'Bob'; // This will cause an error or not work properly

// Right way:
session_start();
$_SESSION['user'] = 'Bob';
?>
📊

Quick Reference

StepDescriptionCode Example
1Start or resume sessionsession_start();
2Set session variable$_SESSION['key'] = 'value';
3Access session variableecho $_SESSION['key'];
4Unset session variableunset($_SESSION['key']);
5Destroy sessionsession_destroy();

Key Takeaways

Always call session_start() before setting or accessing session variables.
Use the $_SESSION superglobal array to set session variables with key-value pairs.
Session variables persist across pages until unset or session is destroyed.
Avoid outputting HTML before session_start() to prevent errors.
Use unset() or session_destroy() to remove session data when needed.