Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Login and Logout using Sessions and Cookies (http://www.go4expert.com/articles/login-logout-using-sessions-cookies-t361/)

shabbir 15Jun2005 12:30

Login and Logout using Sessions and Cookies
 
1 Attachment(s)
This is a very simple code and hardly requires any explanations. :eek: 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

ali07tufat80 1Jul2006 14:32

Re: Login and Logout using Sessions and Cookies
 
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

shabbir 2Jul2006 03:18

Re: Login and Logout using Sessions and Cookies
 
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

intel17 2Jul2006 03:31

Re: Login and Logout using Sessions and Cookies
 
Thanks and great job :P

patrick 6Sep2006 04:01

Re: Login and Logout using Sessions and Cookies
 
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?

shabbir 6Sep2006 06:18

Re: Login and Logout using Sessions and Cookies
 
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.

ted_chou12 21Nov2006 18:41

Re: Login and Logout using Sessions and Cookies
 
does anyone know how to add mutiple accounts to this script?

ted_chou12 21Nov2006 19:14

Re: Login and Logout using Sessions and Cookies
 
*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.

pradeep 22Nov2006 21:34

Re: Login and Logout using Sessions and Cookies
 
Multiple sessions cannot be added to this script, only one user per session/per browser can be logged in at a time.

ted_chou12 22Nov2006 21:35

Re: Login and Logout using Sessions and Cookies
 
oh, okay thanks!

ted_chou12 25Nov2006 22:33

Re: Login and Logout using Sessions and Cookies
 
by the way, where do I place my html code?

pradeep 27Nov2006 13:11

Re: Login and Logout using Sessions and Cookies
 
Place the HTML preferably after the session PHP code.

ted_chou12 27Nov2006 18:38

Re: Login and Logout using Sessions and Cookies
 
<?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>";
?>

pradeep 28Nov2006 10:09

Re: Login and Logout using Sessions and Cookies
 
Yeah, right! But you may need to include or require your files before that, you can include your files, before the session code.

ted_chou12 30Nov2006 19:03

Re: Login and Logout using Sessions and Cookies
 
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?

pradeep 30Nov2006 21:19

Re: Login and Logout using Sessions and Cookies
 
It would be something like this

Code: PHP

<?
$username = $_SESSION['usr'];
$pwd = $_SESSION['pwd'];

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


ted_chou12 1Dec2006 14:06

Re: Login and Logout using Sessions and Cookies
 
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?

ted_chou12 1Dec2006 14:08

Re: Login and Logout using Sessions and Cookies
 
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.

pradeep 1Dec2006 14:09

Re: Login and Logout using Sessions and Cookies
 
\n stands for newline. Visit http://in2.php.net/types.string for more escape sequences.

pradeep 1Dec2006 14:13

Re: Login and Logout using Sessions and Cookies
 
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.

ted_chou12 1Dec2006 14:54

Re: Login and Logout using Sessions and Cookies
 
can you write an eg. and send the file to me with zip?

ted_chou12 1Dec2006 15:17

Re: Login and Logout using Sessions and Cookies
 
i just want a simple example. With the username and age in the text file and the codes that you have to include in the php page, thanks so much.

ted_chou12 2Dec2006 22:36

Re: Login and Logout using Sessions and Cookies
 
spiderman, you not there...? HELP ASAP

pradeep 3Dec2006 01:08

Re: Login and Logout using Sessions and Cookies
 
Try this out, hope you got the point!

Code: PHP

<?
/*
**  Our text file's format is values separated by #
**  And example entry would look like this
**  pradeep#myPassword#Kolkata
*/


$TEXT_FILE = 'data.txt';
$aData = @file($TEXT_FILE); // collect all data into an array

// Dummy data
$user = 'pradeep';
$pwd = 'g4e';

foreach($aData as $v)
{
    list($u,$p,$c) = explode("#",$v); // split up the differnt parts of the data

    if($u == $user && $p == $pwd)
    {
        print "Matched";
        break;
    }
}

?>


Sample text file:
Code:

pradeep#g4e#Kolkata
shabbir#G4E#Kolkata
manindar#ABC#Mumbai


ted_chou12 3Dec2006 01:54

Re: Login and Logout using Sessions and Cookies
 
hey, thanks a lot. it finally worked :) :cool:

ted_chou12 3Dec2006 21:37

Re: Login and Logout using Sessions and Cookies
 
hi, again.
As i got this to work, things got more complicated, here
PHP Code:

<?php
$bData 
= @file("../admin/log_files/members_list.txt"); 
foreach(
$bData as $w){list($username1,$username2,$username3) = explode(":",$w);
$aData = @file("../admin/log_files/members_list.txt"); // collect all data into an array
foreach($aData as $v){list($username,$email,$time) = explode(":",$v); // split up the differnt parts of the data?
echo "<table><tr><td><font face=\"arial\" size=5><b>Last Modification:</b></td><td>$username</td></tr></font>";
echo 
"<tr><td><font face=\"arial\" size=5><b>Name:</b></td><td>$email</td></tr></font>";
echo 
"<tr><td><font face=\"arial\" size=5><b>Gender:</b></td><td>$time</td></tr></font></table>";}}
?>

Now I have two layers, I separated each username with # and the user data with :, and i want to ask if the "$username1,$username2,$username3..." part streches to infinity, what shall i put in? :confused:

pradeep 4Dec2006 10:14

Re: Login and Logout using Sessions and Cookies
 
Code: PHP

<?
// Simple just do this
$aUserList = explode("#",$v);
// This returns an array
?>


ted_chou12 4Dec2006 14:50

Re: Login and Logout using Sessions and Cookies
 
oh, so you dont separte the data?

ted_chou12 4Dec2006 15:01

Re: Login and Logout using Sessions and Cookies
 
Can you give me another example please?
I cant get it to work
ps. please do include the txt file as well, a big "pre"thanks!

cyberience 5Dec2006 12:51

Re: Login and Logout using Sessions and Cookies
 
Good script, got a question though, if we have multiple servers with various configurations in load balancing, and we try to maintain a session, that session will be lost when either round robin on next connection is in effect, so sessions is not an option due to persistence issues, and we don't want to enable persistence through the firewall, as it is not under our control. so we would need to rely on the cookie credentials for every page call to validate the user log in!
also, due to distributed database architecture, we can not maintain credentials in the database either. So we would need to take the cookie credentials and validate on every page. and pass other data via http header.

What is the modification to this script if sessions are not available, but still maintain security?

ubye 8Feb2007 07:42

Re: Login and Logout using Sessions and Cookies
 
i need more explanation about that code..please help me

pradeep 8Feb2007 10:25

Re: Login and Logout using Sessions and Cookies
 
The code snippet provided is quite self-explanatory, what exactly are you failing to understand?

qaladien 1Mar2007 04:39

Re: Login and Logout using Sessions and Cookies
 
I am attemptin gto modify your script to work on my server as a session / user manager authenticator. Logically i can follow th eprogram flow, but I am running in to 2 issues which i hope you are able to assit me with. Any help would be appreciated.

1.) Inside "function confirmUser" i have added the following text to connect to my database and get the information i want to verify (tested this portion alone in a test.php file and i get success when echoing "SUCCESS" on return true)


<----- BEGIN CODE SNIPPET

Code:

//Connecting, selecting database
$link = mysql_connect('X.X.X.X,'USER','PWORD') or die('Could not connect: ' . mysql_error());
mysql_select_db('DBASE') or die('Could not select database');

//DO QUERY
$query = 'SELECT username,password FROM users WHERE username='.$username;
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
$md5pass = md5($password);

//VALIDATE LOGON
    if($username == $data[username] && $md5pass == $data[password])
                return true;
    else
                return false;
}


^----- END CODE SNIPPET


2. Inside login.php, the section as below is not passing errors when username/pword are blank


<------ BEGIN CODE SNIPPET
Code:

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");
    }

^----- END CODE SNIPPET


The page index.php correctly passes me to login.php, i enter a username password, and get returned to the login UName PWord boxes with no error output. Thanks for any assistance and nice elegant code that was easy to follow barring this issue.



Qaladien

pradeep 1Mar2007 09:26

Re: Login and Logout using Sessions and Cookies
 
Try writing

Code: PHP

//DO QUERY
$query = 'SELECT username,password FROM users WHERE username='.$username;


As

Code: PHP

//DO QUERY
$query = sprintf('SELECT username,password FROM users WHERE username="%s" AND password=MD5("%s")',$username,$password);
$r = mysql_query($query);
if(mysql_num_rows($r)>0)
{
  //Success
}


qaladien 1Mar2007 10:15

Re: Login and Logout using Sessions and Cookies
 
the password is stored in the database as MD5 not in raw form so i can drop the MD5 you have in the variable right?

pradeep 1Mar2007 10:18

Re: Login and Logout using Sessions and Cookies
 
yeah right!

asgard2005 23Mar2007 06:44

Re: Login and Logout using Sessions and Cookies
 
Hi, am I right in seeing that login.php calls confirmUser() with a plaintext password but if a cookie is present and its called from the checkloggedin() function the password is sent to confirmuser() in MD5 format?

shabbir 23Mar2007 09:35

Re: Login and Logout using Sessions and Cookies
 
Quote:

Originally Posted by asgard2005
Hi, am I right in seeing that login.php calls confirmUser() with a plaintext password but if a cookie is present and its called from the checkloggedin() function the password is sent to confirmuser() in MD5 format?

The point you are making is correct. You need to have a new flag in confirmUser where you know if its plain or encrypted to fix the issue. Very nice point I must say. I guess if I get time I will definitely update the article.

asgard2005 23Mar2007 10:09

Re: Login and Logout using Sessions and Cookies
 
Quote:

Originally Posted by shabbir
The point you are making is correct. You need to have a new flag in confirmUser where you know if its plain or encrypted to fix the issue. Very nice point I must say. I guess if I get time I will definitely update the article.


In login.php just change it to:
if(confirmuser($username,md5($password)))


works since the session and cookie stored password is MD5 always.

shabbir 23Mar2007 10:52

Re: Login and Logout using Sessions and Cookies
 
I have rectified the error.


All times are GMT +5.5. The time now is 09:25.