I use this simple Login Form, when I don't have to use Ajax. This simple form validate fields with PHP and also check Username and Password with PHP and MySQL. It is obvious that POST values need to refresh page unlike using jQuery Ajax. I write the next post to show using jQuery Ajax in a Login Form.
1. Add this simple form to your HTML:
<form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method = "post" autocomplete="on"> <fieldset> <legend>Login Form</legend> <label for="username">* Username</label> <input type="text" name="username" placeholder="Username"> <label for="password">* Password</label> <input type="password" name="password" placeholder="Password"> </fieldset> <input type="submit" name="login" value="Login" /> </form>
2. I use these codes to show Warnings and Errors. Add it after Form:
<?php if (isset($results['errorMessage'])) { ?> <div class="errorMessage"><?php echo $results['errorMessage'] ?></div> <?php } ?>
3. Add these PHP codes to that file, in top of page. As you know, you need to CONNECT TO DB:
<?php if($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["username"])) { $results['errorMessage'] = "Empty Username!"; } elseif (empty($_POST["password"])) { $results['errorMessage'] = "Empty Password!"; } else { $posted_username = mysqli_real_escape_string($db,$_POST['username']); $posted_password = hash('ripemd160', mysqli_real_escape_string($db,$_POST['password'])); //encode password for security, and also for signup $query = "SELECT * FROM users WHERE username = '$posted_username' AND password = '$posted_password'"; if ($result = mysqli_query($db,$query)) { $row = mysqli_fetch_array($result, MYSQLI_ASSOC); $count = mysqli_num_rows($result); if ($count == 1) { $_SESSION['login_user'] = $posted_username.'*'.$posted_password; //custom session header("Refresh:0"); } else { $results['errorMessage'] = "Please check your Username and/or Password!"; } } } } ?>
4. Now you can check session for logged users:
<?php if (isset($_SESSION['login_user'])) { // Add code for this users ... } ?> <a href = "logout.php">Exit</a>
5. Add these codes to logout.php. After connecting to DB and also starting session:
<?php unset($_SESSION["login_user"]); mysqli_close($db); if(session_destroy()) { header( "refresh:1;url=index.php" ); } ?>