What are some best practices for handling login systems in PHP, especially when using MySQL and sessions?

When handling login systems in PHP with MySQL and sessions, it is important to securely store user passwords using hashing algorithms like bcrypt, sanitize input data to prevent SQL injection attacks, and use sessions to keep track of user authentication status. Additionally, always validate user input and implement proper error handling to provide a smooth user experience.

// Sample code for handling login system in PHP with MySQL and sessions

// Start session
session_start();

// Include database connection file
include 'db_connection.php';

// Sanitize user input
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Query to fetch user data from database
$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 1) {
    $user = mysqli_fetch_assoc($result);
    // Verify password using password_verify function
    if (password_verify($password, $user['password'])) {
        // Set session variables
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        // Redirect user to dashboard or home page
        header('Location: dashboard.php');
        exit();
    } else {
        // Invalid password
        echo "Invalid password";
    }
} else {
    // User not found
    echo "User not found";
}