Add “Remember Me” Feature to Your Login Page Using PHP

Add Remember Me PHP
Most websites have “remember me” or “stay signed in” feature in their login page. By checking that option you will be able to go to your profile page or the page after login, without logging in again. If you visit the home page, you will be redirected to your profile or relevant pages automatically.

Why “Remember Me” Functionality?

  • If a user has a device which is used only by themselves, They can utilize this feature to reduce the time taken for logging in.
  • Some people always forget their login credentials, In this case you don’t have to worry when you are able to login automatically.
We are going to create a simple login functionality with “Remember Me” checkbox option. For this tutorial we have four PHP pages such as index.php, login.php, home.php and logout.php

 

 

index.php

Index page has a simple login form with a checkbox named “remember“. This form data will be sent to login.php.
At the beginning of the page we are checking whether any cookie variable or session variable is set or not. If anyone of it is available we have to redirect users directly to home.php page.

login.php

First we have to get the id or an equivalent field from database if the login credentials is matched. If no one is matched you can show some alert kind of thing.
Then if the checkbox is checked we have to create a cookie variable named “user” with the value of the fetched id. We can set expiry date or time for the cookie, but it is optional. If you don’t give any expiry time, the user will be logged in forever until they manually clear cookies or logout of their account.
If the checkbox is not checked we have to create a session variable with the name “user” and the value of the id.
Finally, we are redirecting the page to home.page or any profile kind of page.

home.php

At first, we are checking either a cookie or a session is set or not, if yes we have to get the user id and fetch user data from database otherwise we have to redirect user to index page.
Also we have a logout page anchor, by visiting the page user can flush the session and cookies from the browser to make them no longer logged in.

logout.php

There is no direct method to delete a cookie in PHP, so we are setting a past time as expiry period, so that the browser will automatically remove it.
Once everything is done, we have to redirect the page to index.php
Download and use this code and give your feedback below. Also subscribe for our feed to get notified about posts instantly.

0 comments :