PHP $_SESSION Reference

beginner
18 min

PHP $_SESSION Reference

Welcome to this comprehensive guide on using PHP $_SESSION! By the end of this tutorial, you'll understand how to manage user sessions in your PHP applications. 🎯

What is a Session in PHP?

A PHP session is a way of storing and retrieving data across multiple page requests. This is particularly useful for keeping track of user data, such as login status, preferences, and shopping cart items. πŸ“

Creating and Managing Sessions

Setting Session Variables

To set a session variable, use the $_SESSION superglobal array:

php
// Start the session session_start(); // Set a session variable $_SESSION['username'] = 'John Doe';

Accessing Session Variables

Access session variables just like any other array:

php
// Access a session variable echo $_SESSION['username']; // Outputs: John Doe

Destroying Sessions

To destroy a session, use the session_destroy() function:

php
// Destroy the session session_destroy();

Session Lifetime and Configuration

By default, PHP sessions last until the user closes their browser. However, you can change this behavior by configuring session settings. Here's how to set a session lifetime of 3600 seconds (1 hour):

php
// Session configuration ini_set('session.gc_maxlifetime', 3600);

Security Considerations

It's essential to secure your sessions to protect user data. You can set the secure and http_only flags to make sessions more secure:

php
// Session configuration session_set_cookie_params(3600, "/", null, true, true);

πŸ’‘ Pro Tip: Always use HTTPS when handling sensitive data, and never store sensitive information directly in sessions!

Real-world Example: User Login

Let's create a simple login system that stores the user's username in the session:

login.php

php
// Start the session session_start(); // Check if the user submitted the login form if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Validate the login credentials // ... // If valid, set the username in the session $_SESSION['username'] = $username; } // Redirect the user to the dashboard header('Location: dashboard.php');

dashboard.php

php
// Start the session session_start(); // Check if the user is logged in if (!isset($_SESSION['username'])) { // Redirect the user to the login page header('Location: login.php'); exit(); } // Display the user's username echo 'Welcome, ' . $_SESSION['username'] . '!';

Quiz

Quick Quiz
Question 1 of 1

What does the `session_start()` function do?

By now, you should have a solid understanding of using the PHP $_SESSION to manage user sessions in your applications. Happy coding! πŸŽ‰