How secure is using SESSION for login scripts in PHP?

Using SESSION for login scripts in PHP can be secure if implemented correctly. To ensure security, make sure to use HTTPS to encrypt data transmission, regenerate the session ID after a successful login, and store sensitive information in the session data. Additionally, always validate user input and use prepared statements to prevent SQL injection attacks.

// Start the session
session_start();

// Check if the user credentials are valid
if ($valid_credentials) {
    // Regenerate session ID
    session_regenerate_id(true);

    // Store user information in the session
    $_SESSION['user_id'] = $user_id;
    $_SESSION['username'] = $username;
    
    // Redirect to the dashboard
    header('Location: dashboard.php');
    exit();
} else {
    // Display error message
    echo 'Invalid credentials';
}