What are the best practices for securely storing and retrieving user IDs in PHP sessions for profile management?

When storing and retrieving user IDs in PHP sessions for profile management, it is important to ensure that the data is securely handled to prevent unauthorized access or tampering. One best practice is to use session encryption to protect sensitive information. Additionally, always validate and sanitize user input to prevent injection attacks.

// Start the session
session_start();

// Store the user ID securely in the session
$_SESSION['user_id'] = encrypt($user_id);

// Retrieve the user ID securely from the session
$user_id = decrypt($_SESSION['user_id']);

// Function to encrypt data
function encrypt($data) {
    $key = "your_secret_key";
    return openssl_encrypt($data, "AES-128-ECB", $key);
}

// Function to decrypt data
function decrypt($data) {
    $key = "your_secret_key";
    return openssl_decrypt($data, "AES-128-ECB", $key);
}