1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Login and Logout using Sessions and Cookies

Discussion in 'PHP' started by shabbir, Jun 15, 2005.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83
    This is a very simple code and hardly requires any explanations. :eek: If you need any put the post here.

    functions.php
    PHP:
    <?php

    function createsessions($username,$password)
    {
        
    //Add additional member to Session array as per requirement
        
    session_register();

        
    $_SESSION["gdusername"] = $username;
        
    $_SESSION["gdpassword"] = md5($password);
        
        if(isset(
    $_POST['remme']))
        {
            
    //Add additional member to cookie array as per requirement
            
    setcookie("gdusername"$_SESSION['gdusername'], time()+60*60*24*100"/");
            
    setcookie("gdpassword"$_SESSION['gdpassword'], time()+60*60*24*100"/");
            return;
        }
    }

    function 
    clearsessionscookies()
    {
        unset(
    $_SESSION['gdusername']);
        unset(
    $_SESSION['gdpassword']);
        
        
    session_unset();    
        
    session_destroy(); 

        
    setcookie ("gdusername""",time()-60*60*24*100"/");
        
    setcookie ("gdpassword""",time()-60*60*24*100"/");
    }

    function 
    confirmUser($username,$password)
    {
        
    // $md5pass = md5($password); // Not needed any more as pointed by ted_chou12

        /* Validate from the database but as for now just demo username and password */
        
    if($username == "demo" && $password "demo")
            return 
    true;
        else
            return 
    false;
    }

    function 
    checkLoggedin()
    {
        if(isset(
    $_SESSION['gdusername']) AND isset($_SESSION['gdpassword']))
            return 
    true;
        elseif(isset(
    $_COOKIE['gdusername']) && isset($_COOKIE['gdpassword']))
        {
            if(
    confirmUser($_COOKIE['gdusername'],$_COOKIE['gdpassword']))
            {
                
    createsessions($_COOKIE['gdusername'],$_COOKIE['gdpassword']);
                return 
    true;
            }
            else
            {
                
    clearsessionscookies();
                return 
    false;
            }
        }
        else
            return 
    false;
    }
    ?>
    index.php
    PHP:
    <?php
    ob_start
    ();
    session_start();

    require_once (
    "functions.php");

    if (
    checkLoggedin())
        echo 
    "<H1>You are already logged in - <A href = \"login.php?do=logout\">logout</A></h1>";
    else
        echo 
    "<H1>You are not logged in - <A href = \"login.php\">login</A></h1></h1>";
    ?>
    login.php
    PHP:
    <?php

    ob_start
    ();
    session_start();

    require_once (
    "functions.php");

    $returnurl urlencode(isset($_GET["returnurl"])?$_GET["returnurl"]:"");
    if(
    $returnurl == "")
        
    $returnurl urlencode(isset($_POST["returnurl"])?$_POST["returnurl"]:"");

    $do = isset($_GET["do"])?$_GET["do"]:"";

    $do strtolower($do);

    switch(
    $do)
    {
    case 
    "":
        if (
    checkLoggedin())
        {
            echo 
    "<H1>You are already logged in - <A href = \"login.php?do=logout\">logout</A></h1>";
        }
        else
        {
            
    ?>
            <form NAME="login1" ACTION="login.php?do=login" METHOD="POST" ONSUBMIT="return aValidator();">
            <input TYPE="hidden" name="returnurl" value="<?$returnurl?>">
            <TABLE cellspacing="3">
            <TR>
                <TD>Username:</TD>
                <TD><input TYPE="TEXT" NAME="username"></TD>
                <TD>Password:</TD>
                <TD><input TYPE="PASSWORD" NAME="password"></TD>
            </TR>
            <TR>
                <TD colspan="4" ALIGN="center"><input TYPE="CHECKBOX" NAME="remme">&nbsp;Remember me for the next time I visit</TD>
            </TR>
            <TR>
                <TD ALIGN="CENTER" COLSPAN="4"><input TYPE="SUBMIT" name="submit" value="Login"></TD>
            </TR>
            </form>
            </TABLE>
        <?
        }
        break;
    case "login":
        $username = isset($_POST["username"])?$_POST["username"]:"";
        $password = isset($_POST["password"])?$_POST["password"]:"";

        if ($username=="" or $password=="" )
        {
            echo "<h1>Username or password is blank</h1>";
            clearsessionscookies();
            header("location: login.php?returnurl=$returnurl");
        }
        else
        {
            if(confirmuser($username,md5($password))) // As pointed out by asgard2005
            {
                createsessions($username,$password);
                if ($returnurl<>"")
                    header("location: $returnurl");
                else
                {
                    header("Location: index.php");
                }
            }
            else
            {
                echo "<h1>Invalid Username and/Or password</h1>";
                clearsessionscookies();
                header("location: login.php?returnurl=$returnurl");
            }
        }
        break;
    case "logout":
        clearsessionscookies();
        header("location: index.php");
        break;
    }
    ?>
    Attachment also modified with a bug as pointed out by asgard2005 here
     

    Attached Files:

    n_javier and emin4 like this.
  2. ali07tufat80

    ali07tufat80 New Member

    Joined:
    Jun 30, 2006
    Messages:
    1
    Likes Received:
    1
    Trophy Points:
    0
    Hello Mr. Shabbir

    I m grateful for this code but can you help me learning php more..

    i have joined a forum www.tufat.com/foums and found it very helpful. but i need your guidence to learn more about php.

    Regards
     
    Darkness_inside likes this.
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83
    Sure. Just put your queries related to PHP in PHP forum and we will definitely help you master in PHP
     
  4. intel17

    intel17 New Member

    Joined:
    Jul 1, 2006
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    Thanks and great job :P
     
  5. patrick

    patrick New Member

    Joined:
    Sep 5, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hello Mr. Shabbir
    The code works well, but after logging out, somebody could hit the back button and see any data on the pages. How difficult would it be to prevent anyong seeing the pages after a logout just like the web sites for all the banks?
     
  6. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83
    For that probably you need to be clearing the cache because thats not the actual page but the cache version and applying some metas can even prevent that.
     
  7. ted_chou12

    ted_chou12 New Member

    Joined:
    Nov 21, 2006
    Messages:
    45
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    does anyone know how to add mutiple accounts to this script?
     
  8. ted_chou12

    ted_chou12 New Member

    Joined:
    Nov 21, 2006
    Messages:
    45
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    *ps. if mutiple accounts are allowed, is it possible to have an echo that shows who is logged in right now? thank you very much, Ted.
     
  9. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Multiple sessions cannot be added to this script, only one user per session/per browser can be logged in at a time.
     
  10. ted_chou12

    ted_chou12 New Member

    Joined:
    Nov 21, 2006
    Messages:
    45
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    oh, okay thanks!
     
  11. ted_chou12

    ted_chou12 New Member

    Joined:
    Nov 21, 2006
    Messages:
    45
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    by the way, where do I place my html code?
     
  12. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Place the HTML preferably after the session PHP code.
     
  13. ted_chou12

    ted_chou12 New Member

    Joined:
    Nov 21, 2006
    Messages:
    45
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    <?php
    ob_start();
    session_start(); ?>
    **********
    You mean here?
    **********
    <? require_once ("functions.php");

    if (checkLoggedin())
    echo "<H1>You are already logged in - <A href = \"login.php?do=logout\">logout</A></h1>";
    else
    echo "<H1>You are not logged in - <A href = \"login.php\">login</A></h1></h1>";
    ?>
     
  14. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Yeah, right! But you may need to include or require your files before that, you can include your files, before the session code.
     
  15. ted_chou12

    ted_chou12 New Member

    Joined:
    Nov 21, 2006
    Messages:
    45
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    okay, ive solved that problem, now, if i want to store username and password in another txt file, what would i have to put in the main php page codes?
    eg.
    Code:
    if(file('logindata.txt'))
    return true;
    else
    return false;
    so far, i tried file(), fileread(), file_ get_ contents(), include(), require()...etc.. and a bunch of them, but none works, can you give me a suggestion?
     
  16. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    It would be something like this

    PHP:
    <?
    $username $_SESSION['usr'];
    $pwd $_SESSION['pwd'];

    $h fopen("userdata.txt");
    fwrite($h,"$username\n$pwd\n\n");
    fclose($h);
    ?>
     
  17. ted_chou12

    ted_chou12 New Member

    Joined:
    Nov 21, 2006
    Messages:
    45
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    where do i paste this in?
    <?$username = $_SESSION['usr'];$pwd = $_SESSION['pwd'];$h = fopen("userdata.txt");fwrite($h,"$username\n$pwd\n\n");fclose($h);?>
    and what do the "\n" stand for?
     
  18. ted_chou12

    ted_chou12 New Member

    Joined:
    Nov 21, 2006
    Messages:
    45
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    oh no, sorry, i think i didn't say it clearly, what i wish is to extract the information of username and password FROM the text file, not store them into the txt files. Thanks for understanding.
     
  19. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
  20. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Well then you have to store the data in text files, in a specific format say user:location:age OR user#ocation#age, so that the data retrieval becomes easy.
    All you have to do is to read the text file line by line, and split it by the separator you have chosen :) or #) and then check the username part for a match. Bingo! you got your record.
     

Share This Page