Search code examples
phpremember-me

How to implement "Remember me"


Sorry I am asking a question that has been asked before but in spite of reading all of them, I am still confused what to do. What exactly I have to do to implement the remember me feature in my website I am building as my final year project. Is calling the function "setcookie()" alone sufficient?


Solution

  • setCookie() is all you need.

    You can use it like this:

    $cookie_value = 'MyUsername';
    $cookie_expire = time() + 60*60*24*365;// 365 days
    $cookie_path = '/';
    setcookie('remember_me',$cookie_value, $cookie_expire, $cookie_path);
    

    On the next pageload, you can fetch the remember_me cookie value with:

    $_COOKIE['remember_me'];
    

    But the 'next pageload' part is important because PHP cookies cannot be set and also read in the same browser action.

    In the most simple way possible. The way I would bring this all together for demonstration for your project is have a php page with an html <form> that posts to itself.

    Your filename would be something like my_form.php

    inside it would be:

    <?php
    //   If we received a username from the form, remember it for a year.
    if( $_POST['username'] ):
         setcookie('remember_me',$_POST['username'], time()+60*60*24*365, '/');
    endif;
    ?>
    
    
    <?php
    //  Display a message if the user is remembered.
    if( isset($_COOKIE['remember_me']) ):
         echo '<h2>Welcome back, '.$_COOKIE['remember_me'].'!</h2>';
    endif;
    ?>
    
    
    <form action="" method="post">
    <input name="username" type="text" placeholder="Your Username" value="<?php echo $_COOKIE['remember_me'] ?>" required />
    <button type="submit">Remember me</button>
    </form>
    

    This form submits to itself. If you see the username you just entered in the welcome message, then it is remembering you.

    Very important! The setcookie() call in PHP must be the first thing in your my_form.php file. Otherwise setcookie() will not work if any output has happened to the web-browser before you call the setcookie() function.