What best practices should be followed when handling session data in PHP to ensure smooth integration with external systems like CMS?

When handling session data in PHP for integration with external systems like CMS, it is important to properly secure the data to prevent unauthorized access or tampering. One best practice is to encrypt the session data before storing it, and decrypt it when retrieving it. This can help protect sensitive information and ensure smooth integration with external systems.

// Encrypt session data before storing
function encrypt_session_data($data, $key) {
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    return base64_encode($iv . $encrypted);
}

// Decrypt session data when retrieving
function decrypt_session_data($data, $key) {
    $data = base64_decode($data);
    $iv = substr($data, 0, openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = substr($data, openssl_cipher_iv_length('aes-256-cbc'));
    return openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv);
}

// Example of encrypting and decrypting session data
$key = 'secret_key';
$_SESSION['user_id'] = encrypt_session_data('12345', $key);

$decrypted_user_id = decrypt_session_data($_SESSION['user_id'], $key);
echo $decrypted_user_id; // Output: 12345