Creating a PHP Session: 3 Practical Examples

Learn how to create PHP sessions with these three practical examples, perfect for beginners and web developers.
By Taylor

Introduction to PHP Sessions

PHP sessions are a way to store information about a user across different pages of your website. This is particularly useful for user authentication, shopping carts, and any situation where you want to retain user data without requiring them to re-enter it on every page. In this article, we’ll go through three detailed examples of creating PHP sessions to help you understand how they work in different contexts.

Example 1: Starting a Basic PHP Session

Use Case

In this example, we will create a simple PHP session to track a visitor’s name. This is a foundational example that demonstrates how to start and use a session.

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

// Store user information in session variables
$_SESSION['username'] = 'JohnDoe';

// Display a message
echo 'Session started. Hello, ' . $_SESSION['username'] . '!';
?>

In this example, we start the session with session_start(), which must be called before any output is sent to the browser. We then set a session variable called ‘username’ and display a greeting message.

Notes

  • Always ensure session_start() is called at the top of your PHP files.
  • Session variables are stored on the server, making them more secure than cookies.

Example 2: Storing User Preferences in a Session

Use Case

This example shows how to create a session that stores user preferences, such as language selection. This is useful for personalizing user experience on your site.

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

// Check if the user has submitted their language preference
if (isset($_POST['language'])) {
    $_SESSION['language'] = $_POST['language'];
}

// Display the selected language or a default
if (isset($_SESSION['language'])) {
    echo 'Selected language: ' . $_SESSION['language'];
} else {
    echo 'No language selected. Defaulting to English.';
}
?>
<form method="post">
    <label for="language">Choose your language:</label>
    <select name="language" id="language">
        <option value="English">English</option>
        <option value="Spanish">Spanish</option>
        <option value="French">French</option>
    </select>
    <input type="submit" value="Set Language">
</form>

In this example, we check if a language preference has been submitted via a form. If it has, we store it in the session. If not, we display a default message.

Notes

  • You can expand this example by adding more user preferences, like theme color or layout settings.
  • Make sure to validate user input to prevent security issues.

Example 3: User Login System with Sessions

Use Case

Here, we will create a simple login system that uses PHP sessions to keep track of logged-in users. This is an essential feature for most web applications.

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

// Simulated user data (in a real app, you would retrieve this from a database)
$valid_username = 'admin';
$valid_password = 'password123';

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validate credentials
    if ($username === $valid_username && $password === $valid_password) {
        // Store user information in session variables
        $_SESSION['loggedin'] = true;
        $_SESSION['username'] = $username;
        echo 'Login successful! Welcome, ' . $_SESSION['username'] . '!';
    } else {
        echo 'Invalid username or password!';
    }
}
?>
<form method="post">
    <label for="username">Username:</label>
    <input type="text" name="username" required>
    <br>
    <label for="password">Password:</label>
    <input type="password" name="password" required>
    <br>
    <input type="submit" value="Login">
</form>

In this example, we simulate a login process where a user enters their username and password. If the credentials match our predefined valid credentials, we create session variables to keep the user logged in.

Notes

  • In a real application, always hash passwords and store them securely in a database.
  • Implement session expiration and logout functionality for improved security.