The PHP Remember Me Tutorial

Save

Using PHP to create a "Remember me" check box gives users the option of being logged in automatically when they visit a site saving them from having to enter their username and password every time they close the browser window. The "Remember me" check box can also be labeled "Keep me logged in" or "Stay signed in." Some sites even give a time-limit for how long it will automatically log you in, such as "Keep me signed in for 2 weeks."

INSTRUCTIONS

  • Create a check box by adding an input tag of the type "checkbox" and a label directly after the input tag. It should be located after the login fields (e.g. Username and Password) and before the submit button. Example code:

    <p><input type="checkbox" name="remember">Remember me</p>

  • Add an "if" statement that checks if the "Remember me" check box is checked or not and, if it is, sets the username cookie to the username in the $_SESSION variable and the password cookie to the password in the $_SESSION variable. It should be located after the code that sets the $_SESSION variables to log the user in. Example code:

    if (isset($_POST['remember'])){

      setcookie("cookname", $_SESSION['username'], time()+2592000, "/");

    setcookie("cookpass", $_SESSION['password'], time()+2592000, "/");

    }

  • Add another "if" statement that checks the users cookies for the username and password then sets the $_SESSION username to the $_COOKIE username and the $_SESSION password to the $_COOKIE password. Example code:

    if (isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){

      $_SESSION['username'] = $_COOKIE['cookname'];

    $_SESSION['password'] = $_COOKIE['cookpass'];

    }

  • Add another "if" statement at the beginning of your logout code that will unset the cookies if the user logs out. The "if" statement should check if the cookies are set and, if they are, set them to empty with a negative expiration. Example code:

    if (isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){

      setcookie("cookname", "", time()-2592000, "/");

    setcookie("cookpass", "", time()-2592000, "/");

    }

Tips & Warnings

  • Storing the username and password in cookies presents certain security risks. Make sure your passwords are always encrypted.
  • This tutorial specifies a 30 day expiration (60 seconds x 60 minutes x 24 hours x 30 days = 2592000 seconds) for the cookie which may be too long or not long enough for your uses.
  • Be sure to edit the example code so that it complies with your code. This includes but is not limited to changing variable names.

References

  • Photo Credit Dynamic Graphics Group/Dynamic Graphics Group/Getty Images
Promoted By Zergnet

Comments

Resources

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!