May 7, 2016
How to create a Login Page with ‘remember me’ option using Cookies in PHP

Hi, friends now we are going to learn how to create a login page with ‘remember me’ option using cookies in PHP. In this, I have used PHP cookies for store username & password. To store login details I have used remember me functionality. If the user comes to the login page, then at that time the user details can be stored in cookies. So the user attempt decreased and stop to type login details for each time.
login.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php session_start(); $conn = new mysqli('localhost', 'root', '', 'test') or die(mysqli_error()); if(isset($_POST["submit"])){ $sql = "SELECT * FROM userpass WHERE user = '".$_POST["name"]. "' AND pass = '" .$_POST["pass"]."'"; $query = mysqli_query($conn, $sql); $res = mysqli_fetch_assoc($query); if($res) { if(!empty($_POST["remember"])) { setcookie ("user", $_POST["name"], time() + (10 * 365 * 24 * 60 * 60)); setcookie ("pass", $_POST["pass"], time() + (10 * 365 * 24 * 60 * 60)); } else { if(isset($_COOKIE["user"])) { setcookie ("user", ""); } if(isset($_COOKIE["pass"])) { setcookie ("pass", ""); } } header("Location:welcome.php"); } else { $msg = "Invalid Username or Password"; } } ?> <!doctype html> <html> <head> <title>SoftAOX | Login</title> </head> <body> <form action="" method="post"> <label>Username</label> <input type="text" name="name" value="<?php if(isset($_COOKIE["user"])) {echo $_COOKIE["user"];} ?>"/><br/><br/> <label>Password</label> <input type="password" name="pass" value="<?php if(isset($_COOKIE["pass"])) {echo $_COOKIE["pass"];}?>"/><br/><br/> <input type="checkbox" name="remember" <?php if(isset($_COOKIE["user"])) { ?> checked <?php }?>/> <label>Remember me</label><br/><br/> <input type="submit" name="submit" value="Login"> <p><?php if(isset($msg)) {echo $msg;} ?></p> </form> </body> </html> |
welcome.php
1 2 3 4 5 6 7 8 9 10 11 12 |
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Welcome to SoftAOX</title> </head> <body> <h1 align="center">Welcome to SoftAOX</h1> <p align="center">This is a PHP autologin ('Remember me') Tutorial</p> <p align="center"><a href="logout.php">Logout</a></p> </body> </html> |
logout.php
1 2 3 4 5 |
<?php session_start(); session_destroy(); header("Location:login.php"); ?> |
Download
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]