How can PHP sessions and MySQL be used to create a secure user profile system in a social network?

To create a secure user profile system in a social network using PHP sessions and MySQL, you can authenticate users upon login, store user information in a MySQL database, and use PHP sessions to maintain user sessions securely. By encrypting sensitive user data before storing it in the database and validating user input to prevent SQL injection attacks, you can enhance the security of the user profile system.

// Start the session
session_start();

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check if user is logged in
if(isset($_SESSION['user_id'])){
    // Fetch user data from database
    $user_id = $_SESSION['user_id'];
    $query = "SELECT * FROM users WHERE id = $user_id";
    $result = mysqli_query($connection, $query);
    $user = mysqli_fetch_assoc($result);

    // Display user profile information
    echo "Welcome, " . $user['username'] . "!";
} else {
    // Redirect to login page if user is not logged in
    header("Location: login.php");
    exit();
}