How can PHP sessions be effectively used to authenticate and authorize users when processing sensitive transactions like money transfers?

To authenticate and authorize users when processing sensitive transactions like money transfers, PHP sessions can be effectively used to store user authentication information such as user ID or role. Upon successful login, a session can be created and checked on each sensitive transaction to ensure the user is authorized to perform the action.

// Start the session
session_start();

// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    // Redirect to login page or display an error message
    header("Location: login.php");
    exit();
}

// Check if the user is authorized to perform money transfers
if ($_SESSION['role'] !== 'admin') {
    // Redirect to unauthorized page or display an error message
    header("Location: unauthorized.php");
    exit();
}

// Proceed with the money transfer process
// Code for money transfer process here