The Wayback Machine - https://web.archive.org/web/20240827223054/https://www.geeksforgeeks.org/best-approach-for-keep-me-logged-in-using-php/
Open In App

Best approach for “Keep Me Logged In” using PHP

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We all have noticed the “Keep Me Logged In” checkbox in most of the websites we log in to. There are different ways and approaches to achieve this through code. The best approach among those is saving the User information in the user browser as cookies. Basically, we have to store both the Username and the Password in the user’s browser as cookies. Then every time the page loads the session variable will be set. Hence the user can log in without having to enter the Username and Password again until the life of that cookie expires. The example code given below is the way how to remember password checkbox works through PHP.

Example

php
<?php
session_start();
if (isset($_SESSION["name"]))
{
    header("location:home.php");
}
$connect = mysqli_connect("localhost", "root", "", "testing");
if (isset($_POST["login"]))
{
    if (!empty($_POST["user_name"]) && !empty($_POST["user_password"]))
    {
        $name = mysqli_real_escape_string($connect, $_POST["user_name"]);
        $password = md5(mysqli_real_escape_string($connect,
                                               $_POST["user_password"]));
        $sql = "Select * from login where name = '" . $name . "
                                   ' and password = '" . $password . "'";
        $result = mysqli_query($connect, $sql);
        $user = mysqli_fetch_array($result);
        if ($user)
        {
            // Saving the username and password as cookies
            if (!empty($_POST["rememberme"]))
            {

                // Username is stored as cookie for 10 years as
                // 10years * 365days * 24hrs * 60mins * 60secs
                setcookie("user_login", $name, time() +
                                    (10 * 365 * 24 * 60 * 60));

                // Password is stored as cookie for 10 years as 
                // 10years * 365days * 24hrs * 60mins * 60secs
                setcookie("user_password", $password, time() +
                                    (10 * 365 * 24 * 60 * 60));

                // After setting cookies the session variable will be set
                $_SESSION["name"] = $name;

            }
            else
            {
                if (isset($_COOKIE["user_login"]))
                {
                    setcookie("user_login", "");
                }
                if (isset($_COOKIE["user_password"]))
                {
                    setcookie("user_password", "");
                }
            }
            header("location:home.php");
        }
        else
        {
            $message = "Invalid Login Credentials";
        }
    }
    else
    {
        $message = "Both are Required Fields. Please fill both the fields";
    }
}
?>

Output

By understanding the above code by reading the comments and explanation you must able to execute the PHP code on the server with storing the Username and Password as cookies in the user’s browser. So in this way remember password task can be achieved.



Similar Reads

How to display logged in user information in PHP ?
In social networking websites like Facebook, Instagram, etc, the username and profile picture of the user that has logged in gets displayed in the header of the website, and that header remains constant, irrespective of the webpage the user has opened. Such functionality can be created by using the session variables. Session variables exist only wh
10 min read
If we delete cookies of a site, we can still logged in without logging again
The facebook is coded in PHP and PHP was launched in 1994. But in PHP, there is a disadvantage i.e if we disable cookies (say in Facebook) the Facebook server will forget the person who has logged in previously and it will take to me that page when that application was launched for the first time. But in Java (JEE Edition, launched in 1999) we have
6 min read
How to redirect a user to the registration if he has not logged in?
Not all content on a website is accessible to all users. There exist some confidential content where only authorized members can access.When a user searches for an IEEE Paper, the IEEE.org displays only the abstract of the paper. To read the whole paper, according to the organization's protocol user requires membership authentication from the organ
4 min read
How to display popup message when logged out user try to vote ?
How users logged in or logged out is detected? When a user satisfies the conditions for login his status changes to logged in. For a website or system to understand that a user is logged in usually a $_SESSION[' '] variable is set as soon as the user logs in. This variable when set helps the website to recognize that a user is present and provides
2 min read
How to keep gap between columns using Bootstrap?
We can keep gap between columns by using normal CSS but here we will use the Bootstrap framework for that. In this article, we will keep a measured gap between columns by the following methods. Using "div" tag: Simply adding a "div" with padding in between two "div" tags gives spacing between the "div". Example: &lt;!DOCTYPE html&gt; &lt;html lang=
2 min read
JavaScript/TypeScript: Standard way to keep the cause of an Error
In this article, we will try to understand that what's the standard way to keep the cause of an Error in JavaScript (or in TypeScript) with the help of certain coding examples. Since there is no such provision provided in JavaScript/TypeScript where directly we may be able to find out the cause of an error (like no such property or in-built method
2 min read
HTTP headers | Keep-Alive
The Keep-Alive header is a general-type header. This header is used to hint at how the connection may be used to set a timeout and a maximum amount of requests. It can also be used to allow a single TCP connection to remain open for multiple HTTP requests/responses (default HTTP connection closed after each request). It is also known as a persisten
2 min read
How to keep compiled files in a separate directory ?
A web project containing HTML, CSS, JavaScript, Images, and Videos files. The task is to ensure that all the files of the project are compiled and bundled to one separate directly. Before we proceed, I would like to give you a brief introduction to parcel-bundler. Parcel-bundler: It is a module that helps to transcribe our ES6+ syntax into a tradit
4 min read
Underscore.js _.keep() Method
The _.keep() method takes an array and a function and hence returns an array generated which keeps only true values based on the conditions of the function. Syntax: _.keep(array, function) Parameters: array: The given array from which the keep array is created.function: The function containing the conditions for elements to be kept. Return Value: T
2 min read
Lodash _.keep() Method
The Lodash _.keep() method takes an array and a function and hence returns an array generated which keeps only true values based on the conditions of the function. Syntax: _.keep( array, function ) Parameters: This method takes two parameters as mentioned above and described below: array: The given array from which keep array is created.function: T
2 min read
Tensorflow.js tf.keep() Function
Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment. The .keep() function is used to hold a tensor input that is formed within a tf.tidy() method from being spontaneously discarded. Syntax: tf.keep(result) Parameters: resu
1 min read
How to add new colors to tailwind-css and keep the originals ones ?
You can easily add new colors to Tailwind CSS and keep the originals ones using customization configuration. You can configure your colors under the colors key in the theme section of your tailwind.config.js file. Follow the below step to add the tailwind.config.js file in your folder. Step 1: Run the below code to your folder's terminal. This will
2 min read
How to keep jQuery UI Accordion collapsed by default ?
In this article, we will learn how to keep jQuery UI Accordion collapsed, by default. This can be done by setting the 'active' property of jQuery Accordion as false. Accordion: It is a way to display collapsible content panels for presenting information in a limited amount of space. By clicking on each panel, we can see the content in it, and using
3 min read
What is the way to keep list of elements straight in HTML file ?
In this article, we will discuss various methods to keep the list of elements straight in an HTML file. Generally, The proper indented content in the browser makes the content well-organized &amp; structured, enhancing the overall readability, along with increasing the interactivity of the website. This could be possible by using the HTML semantic
6 min read
12 Web Development Checklists Every Team Should Keep Handy
A website when build should be attractive, meet the goals of businesses, and be easy to handle. There are various factors that help in keeping it successful. A comprehensive web development checklist can help in delivering a better final product. A checklist is a list that keeps track of items required in order to complete a task given and it can b
6 min read
How to keep a mutable variable in react useRef hook ?
A mutable variable in React is a variable whose value can be changed during the lifetime of a component. Unlike a constant or a state variable, its value can be updated, which can be useful in certain scenarios like maintaining the value of a form input or an element's position on the screen. The useRef hook can be used to create and maintain a mut
2 min read
How to hide an Element Visually but keep it Accessible in CSS?
Hiding an element visually while keeping it accessible for screen readers and assistive technologies involves using CSS techniques. This ensures that the content remains available to users who rely on non-visual interfaces. Table of Content Using visibility: hidden;Using opacity: 0;Using position: absolute;Using visibility: hidden;The element becom
1 min read
JavaScript to keep only first N characters in a string
In this article, we have given a string and the task is to keep only the first n characters of the string using JavaScript. There are various methods to solve this problem, some of which are discussed below: Methods to keep only First N characters in a String:Table of Content Method 1: Using substring() MethodMethod 2: Using slice() MethodMethod 3:
5 min read
How to keep the active pagination (dot) always centered ?
Many times we use a slider to store more than one image or post in one place by utilizing space better. There are many types of sliders available with different pagination styles, number pagination, arrows pagination, draggable slider, etc. In this article, we discuss the dot pagination slider where the active dot is at the center. Approach: We use
3 min read
How to Force Image Resize and Keep Aspect Ratio in HTML ?
When working with images on the web, maintaining the aspect ratio is essential for a visually appealing and consistent presentation. This article explores various approaches to force image resize while preserving the aspect ratio in HTML, covering different methods based on your specific requirements. Method 1: Using CSS max-width and max-height Pr
2 min read
Explain the difference in approach when designing a responsive website over a mobile-first strategy
If you heard about Responsive website design and mobile-first approach, then this article is for you. In this article, we will see what is the difference between Responsive website design and the mobile-first approach. In this article, we covered all necessary questions about Responsive website design and mobile-first like what is mobile-first and
5 min read
Bootstrap 5 Approach z-index Scales
Bootstrap Z-index scales provide a new axis to arrange the content on the screen. It plays a very important role in how components interact with one another. A component with a higher z-index value is always in front of the component with a lower z-index value. Z-index in Bootstrap is of two types Component Elements and Overlay Elements. Component
2 min read
Bootstrap 5 Approach Classes
Bootstrap 5 is a popular front-end framework used by web developers to create responsive and mobile-first websites. One of the most useful features of Bootstrap 5 is the approach classes. Bootstrap 5 Approach Classes are a new set of classes introduced in Bootstrap 5 that allow developers to style components in a more flexible and customizable way.
2 min read
Destructive vs Non-Destructive Approach in JavaScript Arrays
JavaScript provides two approaches to adding elements to an array: destructive and non-destructive. Understanding the difference between them is crucial in developing efficient and error-free code. Destructive Approach: The destructive approach modifies the original array using methods like push(), pop(), shift(), unshift(), etc. One example of the
3 min read
Bootstrap 5 Approach z-index Scales Component Elements
Bootstrap z-index allows providing different axis to the components on the screen. It helps in defining the order of the overlapping elements. It sets the position or order of the elements along the z-axis. An element with a greater z-index will appear before the others. Component elementsPre-built elements like button groups, input groups, and pag
2 min read
React MUI API Design Approach
React MUI is a UI library that provides fully-loaded components, bringing our own design system to our production-ready components. MUI is a user interface library that provides predefined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google. In this articl
4 min read
What is the Utility-First Approach in Tailwind CSS ?
The Utility-First Approach in Tailwind CSS emphasizes building user interfaces by directly applying small, atomic utility classes in your HTML markup. Instead of writing custom CSS rules, developers utilize predefined utility classes to style elements, promoting a more efficient and streamlined development process. Syntax&lt;div class="bg-blue-500
1 min read
How to use media queries in a mobile-first approach in HTML ?
Designing a responsive website layout that adapts to various devices and screen sizes is achievable through the use of media queries. This adaptability is defined by two key parameters: screen width and orientation. There are two primary strategies for creating a responsive website: Mobile-First Approach: This strategy begins with CSS tailored for
4 min read
Bootstrap 5 Approach Responsive
Bootstrap 5 responsive approach ensures web page visibility across devices. Media queries, such as min-width and occasionally max-width, are used to address responsiveness. Efforts are made to minimize reliance on media queries while accommodating complex component needs. Bootstrap 5 Approach Responsive: MixinDescription@include media-breakpoint-on
2 min read
Bootstrap 5 Approach
Bootstrap 5 Approach simplifies customization and extension, providing principles and strategies for tailored development. It manages viewport behavior, ensuring optimal rendering on diverse devices. By setting viewport width and scale, enables responsive design, adjusting content for optimal viewing. Bootstrap 5 facilitates the different approache
3 min read