function login($username, $password, $mysqli) { // Purpose: This function performs user logins // Prepared statements prevents SQLinjections if ($stmt = $mysqli->prepare("SELECT uid, username, password \r\n\t\t\t\t\t\t\t\tFROM users\r\n\t\t\t\t\t\t\t\tWHERE username = ?\r\n\t\t\t\t\t\t\t\tLIMIT 1")) { $stmt->bind_param('s', $username); // Bind '$username' to parameter. $stmt->execute(); // Execute the prepared query. $stmt->store_result(); // Get variables from result. $stmt->bind_result($user_id, $db_username, $db_password); $stmt->fetch(); if ($stmt->num_rows == 1) { // We got a user if (validate_pwd($password, $db_password) == true) { // Yay! Correct password // Get the user-agent string of the user $user_browser = $_SERVER['HTTP_USER_AGENT']; // Filter user_id for XSS protection $user_id = preg_replace("/[^0-9]+/", "", $user_id); $_SESSION['user_id'] = $user_id; // Filter username for XSS protection $username = preg_replace("/[^a-zA-Z0-9_\\-]+/", "", $username); // Hash password for login_string $_SESSION['username'] = $username; $_SESSION['login_string'] = hash('sha512', $db_password . $user_browser); // Login successful. return true; } else { // Password is not correct return false; } } else { // No user exists. return false; } } }
<head> <title>Secure Login page</title> <link rel="stylesheet" href="styles/main.css" /> <script type="text/JavaScript" src="js/forms.js"></script> </head> <body> <?php if (isset($_GET['error'])) { echo '<p class="error">Error Logging In!</p>'; } ?> <form action="includes/process_login.php" method="post" name="login"> Username: <input type="text" name="username" /> Password: <input type="password" name="password" id="password"/> <input type="submit" value="login" /> </form> <?php if (login_check($mysqli) == true) { echo '<p>You are currently logged in as ' . htmlentities($_SESSION['username']) . '.</p>'; } else { echo '<p>You must login to continue</p>'; echo "<p>If you don't have a login, please <a href='register.php'>register</a></p>"; echo validate_pwd('Iamtako0', '$2y$10$4UB63oGKxliaLNfAcgCvs.1irZrUQvJYlLDczYGu3Ih/0YiT6Myky'); } ?> </body> </html>