Remember me feature using cookies in PHP

Remember me feature is used with the login form to store username and password using cookies, so the form gets auto filled with these when we get the form on browser. So, Today I am going explain how to use Remember me feature using cookies in PHP.

First add a remember me checkbox to your login form like below:

<input type="checkbox" id="remember_me" name="remember_me" value="1" /> <label for="remember_me"> Remember Me </label>

Now add following code to your login function after user submits the login form:

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

	// check for user details if valid

	/*remember me*/
	if(isset($formData['remember_me'])){ // if user check the remember me checkbox
		$twoDays = 60 * 60 * 24 * 2 + time();
		setcookie('username', $formData['username'], $twoDays);
		setcookie('password', $formData['password'], $twoDays);
	} else { // if user not check the remember me checkbox
		$twoDaysBack = time() - 60 * 60 * 24 * 2;
		setcookie('username', '', $twoDaysBack);
		setcookie('password', '', $twoDaysBack);

Now in login form assign cookie value to username and password field like below:

<input type="text" name="username" id="username" value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>">

<input type="password" name="password" id="password" value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>">

Now add following to checked remember me checkbox:

<input type="checkbox" id="remember_me" name="remember_me" <?php if(isset($_COOKIE['username'])){echo "checked='checked'"; } ?> value="1" /> <label for="remember_me"> Remember Me </label>

This way you can use remember me feature with login form using cookies in PHP. Hope this tutorial will help you.