Add “Remember Me” Feature to Your Login Page Using 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.
index.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
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
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
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.