What are the best practices for securely accessing and displaying user-specific data in PHP applications?

When accessing and displaying user-specific data in PHP applications, it is important to follow best practices for security to prevent unauthorized access to sensitive information. One way to achieve this is by using session management to authenticate users and control access to their data. Additionally, data should be properly sanitized and validated before displaying it to prevent SQL injection and other security vulnerabilities.

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

// Check if the user is authenticated
if (!isset($_SESSION['user_id'])) {
    // Redirect to the login page if not authenticated
    header("Location: login.php");
    exit();
}

// Retrieve user-specific data from the database
$user_id = $_SESSION['user_id'];
// Perform database query to fetch user data using $user_id

// Display the user-specific data on the page
echo "Welcome, User " . $user_id . "! Your data: " . $user_data;
?>