Login and Logout using Sessions and Cookies

shabbir's Avatar author of Login and Logout using Sessions and Cookies
This is an article on Login and Logout using Sessions and Cookies in PHP.
Rated 5.00 By 1 users
This is a very simple code and hardly requires any explanations. If you need any put the post here.

functions.php
PHP Code:
<?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 Code:
<?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 Code:
<?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
File Type: zip LoginLogout.zip (2.0 KB, 1035 views)
caca, emin4, n_javier likes this
0
ali07tufat80's Avatar, Join Date: Jun 2006
Newbie Member
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 like this
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by ali07tufat80
I m grateful for this code but can you help me learning php more..
Sure. Just put your queries related to PHP in PHP forum and we will definitely help you master in PHP
0
intel17's Avatar, Join Date: Jul 2006
Go4Expert Member
Thanks and great job :P
0
patrick's Avatar, Join Date: Sep 2006
Newbie Member
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?
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
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.
0
ted_chou12's Avatar, Join Date: Nov 2006
Go4Expert Member
does anyone know how to add mutiple accounts to this script?
0
ted_chou12's Avatar, Join Date: Nov 2006
Go4Expert Member
*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.
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Multiple sessions cannot be added to this script, only one user per session/per browser can be logged in at a time.
0
ted_chou12's Avatar, Join Date: Nov 2006
Go4Expert Member
oh, okay thanks!
like this