How can form data be securely stored in a separate array within a session in PHP?

When storing form data in a session in PHP, it's important to securely store sensitive information like passwords or credit card details. One way to do this is to store the form data in a separate array within the session rather than directly assigning form field values to session variables. This helps compartmentalize the data and reduces the risk of exposing sensitive information.

<?php
session_start();

// Initialize an empty array to store form data
if (!isset($_SESSION['form_data'])) {
    $_SESSION['form_data'] = [];
}

// Store form data in the separate array within the session
$_SESSION['form_data']['username'] = $_POST['username'];
$_SESSION['form_data']['email'] = $_POST['email'];
$_SESSION['form_data']['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Access the stored form data
$username = $_SESSION['form_data']['username'];
$email = $_SESSION['form_data']['email'];
$password = $_SESSION['form_data']['password'];
?>