Programming Tools
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
User Name:
Password:
Remember me
 



Go Back   Dev Articles Community ForumsProgrammingProgramming Tools

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Display Modes
 
Unread Dev Articles Community Forums Sponsor:
  #1  
Old March 31st, 2003, 01:15 AM
Mr Chocloate Mr Chocloate is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Aug 2002
Location: Anglesea
Posts: 12 Mr Chocloate User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
That was a great article! very quick and straight to the point.

Do you have that code for download? every time i try and cut and pate it gets really messy. I would love to use it

Reply With Quote
  #2  
Old August 31st, 2003, 12:08 AM
soichih soichih is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 1 soichih User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
cookie bug

I don't know if I am doing wrong, but I tried and tested and with the code on the article, the cookie value will never be set on database, and setcookie function will never be called with updated cookie when user does "remember".

So when user do remember, it won't remember because the value is always null.

How am I supposed to fix this problem?

Reply With Quote
  #3  
Old September 20th, 2003, 09:30 AM
DDDooGGG DDDooGGG is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Dec 2002
Location: Melbourne, Australia
Posts: 97 DDDooGGG User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 23 m 33 sec
Reputation Power: 16
Could someone tell me where and how i use these function in this article?
Can aybody plese leave a full example with HTML included?

thanks.
__________________
regards,


Fulton

Reply With Quote
  #4  
Old September 28th, 2003, 11:13 PM
Dave Cheney Dave Cheney is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Sep 2003
Posts: 3 Dave Cheney User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
member.class.php

Hi,

A good article, but I found that there are some omissions that make it unworkable out of the box. Here is my implementation of the class.

All comments are welcome, and appreciated.

At the moment the class will restore the login on instansiation, but i haven't managed to remove the 'remember' cookie so there is no way to log out at the moment

Cheers

Dave

-----

Quote:

<?php

// member class
// handlers member logon

class member_class
{
function member_class()
{
if (!isset($_SESSION['uid']))
{
$this->set_session_defaults();
}
if ($_SESSION['logged_in'])
{
$this->check_session();
}
if (isset($_COOKIE['remember']))
{
print('checking cookie');
$this->check_remembered($_COOKIE['remember']);
}
}

function check_login($username,$password,$remember)
{
global $db;
$username = mysql_escape_string($username);
$password = mysql_escape_string(md5($password));

print('username:'.$username." password:".$password);

$result=$db->query("SELECT * FROM member WHERE username = '{$username}' AND password = '{$password}'");

if ($db->numrows($result))
{
$this->set_session($db->fetchrow($result),$remember,true);
return true;
} else {
$this->failed = true;
$this->logout();
return false;
}
}

function logout()
{
// blowup cookie
setcookie('remember',null,time()-3600);
$this->set_session_defaults();
}

function set_session($result,$remember,$init = true)
{
global $db;
print('Setting session');

if ($init)
{
$session = mysql_escape_string(session_id());
$ip = mysql_escape_string($_SERVER['REMOTE_ADDR']);
$result['token'] = $this->token(); // generate a new token
$db->query("UPDATE member SET session='{$session}', token='{$result['token']}', ip='{$ip}' WHERE uid='{$result['uid']}'");
}

$_SESSION['uid'] = $result['uid'];
$_SESSION['username'] = htmlspecialchars($result['username']);
$_SESSION['token'] = $result['token'];
$_SESSION['logged_in'] = true;

if ($remember)
{
$this->update_cookie($result['token']);
}

}

function update_cookie($token)
{
$cookie = serialize(array($_SESSION['username'],$token));
setcookie('remember',$cookie, time()+31104000);
}

function check_remembered($cookie)
{
global $db;
var_dump(unserialize($cookie));
list($username,$token) = unserialize($cookie);
if(empty($username) or empty($token))
{
print('cookie error');
return;
} else {
$username = mysql_escape_string($username);
$token = mysql_escape_string($token);

$result = $db->fetchrow($db->query("SELECT * FROM member WHERE username = '{$username}' AND token ='{$token}'"));
var_dump($result);
if ($result != false)
{
$this->set_session($result,false,false);
}
}
}

function token()
{
// generate a random token

for($i=1;$i<33;$i++)
{
$seed .= chr(rand(0,255));
}
return md5($seed);
}

function check_session()
{
global $db;
$username = mysql_escape_string($_SESSION['username']);
$token = mysql_escape_string($_SESSION['token']);
$session = mysql_escape_string(session_id());
$ip = mysql_escape_string($_SERVER['REMOTE_ADDR']);

$result = $db->fetchrow($db->query("SELECT * FROM member WHERE username='{$username}' AND token='{$token}' AND session='{$session}' AND ip='{$ip}'"));
if ($result != false)
{
} else {
$this->logout();
}
}


function set_session_defaults()
{
$_SESSION['logged_in'] = false;
$_SESSION['uid'] = 0;
$_SESSION['username'] = '';
$_SESSION['cookie'] = 0;
$_SESSION['remember'] = false;
}
}
?>


Last edited by Dave Cheney : September 29th, 2003 at 12:49 AM.

Reply With Quote
  #5  
Old September 28th, 2003, 11:19 PM
Dave Cheney Dave Cheney is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Sep 2003
Posts: 3 Dave Cheney User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
logout function

this seams to do the trick

function logout()
{
// blowup cookie
setcookie('remember',time()-3600);
$this->set_session_defaults();
}

Reply With Quote
  #6  
Old September 29th, 2003, 12:52 AM
Dave Cheney Dave Cheney is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Sep 2003
Posts: 3 Dave Cheney User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
db schema for above - slightly modified from the original posted in the article

CREATE TABLE `member` (
`uid` int(11) NOT NULL auto_increment,
`username` varchar(20) NOT NULL default '',
`PASSWORD` varchar(32) binary NOT NULL default '',
`token` varchar(32) binary NOT NULL default '',
`session` varchar(32) binary NOT NULL default '',
`ip` varchar(15) binary NOT NULL default '',
PRIMARY KEY (`uid`),
UNIQUE KEY `username` (`username`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;

Reply With Quote
  #7  
Old January 1st, 2004, 12:28 PM
krose krose is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Dec 2003
Posts: 5 krose User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Dave,

Thank you for posting your update to the Secure Log in Article on the devArticles site (back in Sept 2003). This is the most comprehensive code I have found.

I am trying to implement it, but just have a few questions about when to call certain methods.

Would you be willing to send me a skeleton of a couple of content pages that have the security calls in place?

I am just having trouble with the "big picture" of how it all fits together.

Your help would be greatly appreciated!

Thanks,
Kevin

Reply With Quote
  #8  
Old February 27th, 2004, 11:08 AM
cyomega cyomega is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Feb 2004
Posts: 1 cyomega User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Quote:
Originally Posted by krose
Dave,

Thank you for posting your update to the Secure Log in Article on the devArticles site (back in Sept 2003). This is the most comprehensive code I have found.

I am trying to implement it, but just have a few questions about when to call certain methods.

Would you be willing to send me a skeleton of a couple of content pages that have the security calls in place?

I am just having trouble with the "big picture" of how it all fits together.

Your help would be greatly appreciated!

Thanks,
Kevin


I second this motion. I'm trying to figure out the best way to check login status on the content pages, and bounce back to the login page if the session expires or if the user logs out.

::(`)::

Reply With Quote
  #9  
Old March 12th, 2004, 12:55 AM
TonBao TonBao is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Mar 2004
Posts: 1 TonBao User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Got error!

I've just read ur article and follow it as well. And I've received the following error:

Parse error: parse error, unexpected T_VARIABLE, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in c:\inetpub\wwwroot\My Scripts\Login form\login.php on line 41

the line 41 in my script is $date=gmdate("'Y-m-d'");

Thanks

Reply With Quote
  #10  
Old May 10th, 2004, 04:35 PM
drhetesi drhetesi is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2004
Posts: 1 drhetesi User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
MySQL load

I need to build some authentication for a site of upwards of 1000 people. Is there going to be stress on the MySQL database if its accessed each time a secure page is accessed? Is there a way test this before I go online with it?

Thanks a lot.

The Doctor.

Reply With Quote
  #11  
Old August 27th, 2004, 12:54 PM
trystano trystano is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jul 2003
Posts: 45 trystano User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 15
Hi all,

I know its been a long time, but did anyone actually find out where exactly they need to put the function calls to this class within the HTML?

Thanks

Tryst
__________________
Tryst

Reply With Quote
  #12  
Old August 27th, 2004, 09:35 PM
trystano trystano is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jul 2003
Posts: 45 trystano User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 15
Unserialize Problem

Has anyone else had any problems with the unserialize() function in this script?

Thanks

Tryst

Reply With Quote
  #13  
Old January 16th, 2005, 11:57 AM
TallyHo TallyHo is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jan 2005
Posts: 1 TallyHo User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 m 23 sec
Reputation Power: 0
Thumbs up Old thread but here come the examples

Its an old thread though after checkin out Daves class (nice) i just added a few lines to get it to work and since some people asked for examples on how to use it.. here we go:
file: member_class.php
PHP Code:
<?php
   
// member class
   // handlers member logon
   
class member_class
   
{
   function 
member_class()
   {
   if (!isset(
$_SESSION['uid']))
   {
   
$this->set_session_defaults();
   }
   if (
$_SESSION['logged_in'])
   {
   
$this->check_session();
   }
   if (isset(
$_COOKIE['remember']))
   {
   
//print('checking cookie');
   
$this->check_remembered($_COOKIE['remember']);
   }
   }
   
   function 
check_login($username,$password,$remember)
   {
   global 
$db;
   
$username mysql_escape_string($username);
   
$password mysql_escape_string(md5($password));
   
   
$result=$db->query("SELECT * FROM member WHERE username = '{$username}' AND password = '{$password}'");
   
   if (
$db->num_rows($result))
   {
   
$this->set_session($db->next_record($result),$remember,true);
   return 
true;
   } else {
   
   
$this->failed true;
   
$this->logout();
   return 
false;
   }
   }
   
   function 
logout()
   {
   
// blowup cookie
   
setcookie('remember',time()-3600);
   
$this->set_session_defaults();
   }
   
   function 
set_session($result,$remember,$init true)
   {
   global 
$db;
   
//print('Setting session<br>');
   
$uid=$db->f('uid');
   if (
$init)
   {
   
$session mysql_escape_string(session_id());
   
$ip mysql_escape_string($_SERVER['REMOTE_ADDR']);
   
$newtoken $this->token(); // generate a new token
   
$db->query("UPDATE member SET session='{$session}', token='{$newtoken}', ip='{$ip}' WHERE uid='{$uid}'");
   }
   
   
$_SESSION['uid'] = $db->f('uid');
   
   
$_SESSION['username'] = htmlspecialchars($db->f('username'));
   
$_SESSION['token'] = $newtoken;
   
$_SESSION['logged_in'] = true;
   
   if (
$remember)
   {
   
$this->update_cookie($newtoken);
   }
   
   }
   
   function 
update_cookie($token)
   {
   
$cookie serialize(array($_SESSION['username'],$token));
   
//$cookie = serialize(array('bas','token'));
   
setcookie('remember',$cookietime()+12099600);
   }
   
   function 
check_remembered($cookie)
   {
   global 
$db;
   
   
$serializedArray=$cookie;
   
$serializedArray stripslashes($serializedArray);
   list(
$username,$token) = unserialize($serializedArray);
   
   
   if(empty(
$username) or empty($token))
   {
   
//print('cookie error<br>');
   
return;
   } else {
   
$username mysql_escape_string($username);
   
$token mysql_escape_string($token);
   
$ip mysql_escape_string($_SERVER['REMOTE_ADDR']);
   
$result $db->next_record($db->query("SELECT * FROM member WHERE username = '{$username}' AND token ='{$token}'"));
   
   
//var_dump($result);
   
if (!$result)
   {
   
$this->set_session($result,false,false);
   }else{
   
$this->set_session($result,true,true);
   }
   }
   }
   
   function 
token()
   {
   
// generate a random token
   
for($i=1;$i<33;$i++)
   {
   
$seed .= chr(rand(0,255));
   }
   return 
md5($seed);
   }
   
   function 
check_session()
   {
   global 
$db;
   
$username mysql_escape_string($_SESSION['username']);
   
$token mysql_escape_string($_SESSION['token']);
   
$session mysql_escape_string(session_id());
   
$ip mysql_escape_string($_SERVER['REMOTE_ADDR']);
 
$result $db->next_record($db->query("SELECT * FROM member WHERE username='{$username}' AND token='{$token}' AND session='{$session}' AND ip='{$ip}'"));
   if (
$result != false){
   
   }else{
   
$this->logout();
   }
   }
   
   
   function 
set_session_defaults()
   {
   
$_SESSION['logged_in'] = false;
   
$_SESSION['uid'] = 0;
   
$_SESSION['username'] = '';
   
$_SESSION['cookie'] = 0;
   
$_SESSION['remember'] = false;
   }
   }
   
?>

to use this class i created a file with the following content.
file:test.php
PHP Code:
<?PHP
   session_start
();
   
//include phplib
   
include 'mysql.php';
   
//include the class
   
include 'member_class.php';
   
$db = new DB_Sql;
   
$member_class = new member_class;
   
   
   
$Submit=$_POST['Submit']?TRUE:FALSE;
   if(
$Submit && ($_POST['exit'] == 0)){
   
$username=$_POST['username'];
   
$password=$_POST['password'];
 if(
$_POST['remember'] ==1){
  
$member_class->check_login($username$passwordtrue);
  }else{
  
$member_class->check_login($username$passwordfalse);
  }
   
   }
   if(
$Submit && ($_POST['exit'] == 1)){
   
$member_class->logout();
   }
   
   echo 
'username: '.$_SESSION['username'].'<br>';
   echo 
'<a href="/test.php">test</a>';
   
   if(!
$_SESSION['username']) {
   print 
'<form name="form1" method="post" action="">
     <table border="0">
       <tr>
         <td>u</td>
         <td><input type="text" name="username"></td>
       </tr>
       <tr>
         <td>p</td>
         <td><input type="text" name="password"></td>
       </tr>
       <tr>
         <td><input type="submit" name="Submit" value="Submit"></td>
      <td><input type="hidden" name="exit" value="0"><input name="remember" type="checkbox" id="remember" value="1"> remember me for 2 weeks</td>
       </tr>
     </table>
   </form>'
;
   }elseif(
$_SESSION['username']){
   
//
   
print '<form name="form1" method="post" action="">
     <input type="submit" name="Submit" value="Logout"><input type="hidden" name="exit" value="1">
   </form>'
;
   }
   
?>


Hope i didnt mess anything up, but its pretty straight forward so i didnt need to change too many things to the original class. Its my first post so go easy on me.

Reply With Quote
  #14  
Old April 11th, 2005, 11:15 PM
Miseryshining Miseryshining is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Apr 2005
Posts: 1 Miseryshining User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 19 m 44 sec
Reputation Power: 0
TallyHo, thanks for your example!
It's an even older thread now, but i wanted to share some code for people who don't (want to) use PHPLIB. The database connections are replaced with standard php mysql queries.

Also i added a function to add new accounts and i put in some validation and tidied up some code

file: member_class.php
PHP Code:
<?php
     
// member class
     // handlers member logon
     
class member_class   {
         var 
$message '';
      var 
$query_error 'ERROR: something went wrong when accessing the database. Please consult your webmaster';
  
         function 
member_class()   {   //constructor
             
if (!isset($_SESSION['uid']))   {   //fills session with empty values 
                 
$this->set_session_defaults();
             }
  
             if (
$_SESSION['logged_in'])   {    //already logged in
                 
$this->check_session();
             }
  
             if (isset(
$_COOKIE['remember']))   {  
                 
$this->check_remembered($_COOKIE['remember']);
             }
         }    
     
         function 
register($username,$password,$remember)   {
             
$username mysql_escape_string($username);
                 
$password mysql_escape_string(md5($password));
     
          
$result=mysql_fetch_array(mysql_query("SELECT * FROM member WHERE username = '{$username}'"), MYSQL_ASSOC);
             if (!
$result)   {  //insert record if user name doesn't exist
              
$insert mysql_query("INSERT INTO member VALUES ('', '$username', '$password', '', '', '')") or DIE ($this->query_error);
              
$result mysql_fetch_array(mysql_query("SELECT * FROM member WHERE username = '{$username}' AND password = '{$password}'"), MYSQL_ASSOC) or DIE ($this->query_error);
              
$this->message .= '<p>Registration was successful</p>';
              
$this->set_session($result,$remember,true); //log user on
                    
return true;
             } else {
              
$this->message .= '<p>username already exists! Please choose a different name</p>';
                 return 
false;
             }
         }
  
         function 
check_login($username,$password,$remember)   {
             
$username mysql_escape_string($username);
             
$password mysql_escape_string(md5($password));
     
          
$result=mysql_fetch_array(mysql_query("SELECT * FROM member WHERE username = '{$username}' AND password = '{$password}'"), MYSQL_ASSOC);
             if (
$result)   {
                 
$this->set_session($result,$remember,true);
     
                 return 
true;
             } else {
                 
$this->failed true;
                 
$this->logout();
              
$this->message .= 'incorrect username of password. please try again';
                 return 
false;
             }
         }
     
         function 
logout()   {
             
// blowup cookie
             
setcookie('remember',time()-3600);
             
$this->set_session_defaults();
         }
     
         function 
set_session($result,$remember,$init true)   {
             
$uid=$result['uid'];
             if (
$init)   {
                 
$session mysql_escape_string(session_id());
                 
$ip mysql_escape_string($_SERVER['REMOTE_ADDR']);
              
$newtoken $this->token(); // generate a new token
              
$update mysql_query("UPDATE member SET session='{$session}', token='{$newtoken}', ip='{$ip}' WHERE uid='{$uid}'") or DIE ($this->query_error);
             }
     
             
$_SESSION['uid'] = $result['uid'];
              
$_SESSION['username'] = htmlspecialchars($result['username']);
             
$_SESSION['token'] = $newtoken;
             
$_SESSION['logged_in'] = true;
     
             if (
$remember)   {
                 
$this->update_cookie($newtoken);
             }
     
         }
     
         function 
update_cookie($token)   {
             
$cookie serialize(array($_SESSION['username'],$token));
             
setcookie('remember',$cookietime()+12099600);
         }
     
         function 
check_remembered($cookie)   {
     
             
$serializedArray=$cookie;
             
$serializedArray stripslashes($serializedArray);
             list(
$username,$token) = unserialize($serializedArray);
     
             if(empty(
$username) or empty($token))   {
                 return;
             } else {
                 
$username mysql_escape_string($username);
                 
$token mysql_escape_string($token);
                 
$ip mysql_escape_string($_SERVER['REMOTE_ADDR']);
              
$result mysql_fetch_array(mysql_query("SELECT * FROM member WHERE username = '{$username}' AND token ='{$token}' AND ip = '{$ip}'"), MYSQL_ASSOC) or DIE ($this->query_error);
     
                 if (!
$result)   {
                     
$this->set_session($result,false,false);
                 }else{
                     
$this->set_session($result,true,true);
                 }
             }
         }
     
         function 
token()   {
             
// generate a random token
             
for($i=1;$i<33;$i++)   {
                 
$seed .= chr(rand(0,255));
             }
             return 
md5($seed);
         }
     
         function 
check_session()  {
             
$username mysql_escape_string($_SESSION['username']);
             
$token mysql_escape_string($_SESSION['token']);
             
$session mysql_escape_string(session_id());
             
$ip mysql_escape_string($_SERVER['REMOTE_ADDR']);
          
$result mysql_fetch_array(mysql_query("SELECT * FROM member WHERE username='{$username}' AND token='{$token}' AND session='{$session}' AND ip='{$ip}'"), MYSQL_ASSOC) or DIE ($this->query_error);
  
             if (
$result != false){
             }else{
                 
$this->logout();
             }
         }
     
     
         function 
set_session_defaults()   {
             
$_SESSION['logged_in'] = false;
             
$_SESSION['uid'] = 0;
             
$_SESSION['username'] = '';
             
$_SESSION['cookie'] = 0;
             
$_SESSION['remember'] = false;
         }
     }
  
  
?>

usage example:
file:whatever.php
PHP Code:
<?php
     session_start
();
     include 
'db_connect.php';
     include 
'member_class.php';
     
$member_class = new member_class;
     
     
     
//$Submit=$_POST['Submit']?TRUE:FALSE;
     
if($_POST['Register']) {  //register new user
         
$username $_POST['username'];
         
$password $_POST['password'];
         if (
$username && $password) { //check whether username and password have been submitted
             
if($_POST['remember'] == 1)    {
              
$member_class->register($username$passwordtrue);
             }else{
              
$member_class->register($username$passwordfalse);
             }
         }       
         else {
          
$member_class->message .= '<p>please fill in a user name and password</p>';
             
$_POST['form_register'] = 'true';
         }
     }
     elseif(
$_POST['Login'])      {
         
$username=$_POST['username'];
         
$password=$_POST['password'];
         if (
$username && $password) {
             if(
$_POST['remember'] ==1)    {
              
$member_class->check_login($username$passwordtrue);
             }else{
              
$member_class->check_login($username$passwordfalse);
             }
         }
      else 
$member_class->message .= '<p>please fill in a valid user name and password</p>';
     }
     elseif(
$_POST['Logout'])   {
         
$member_class->logout();
     }
     
     echo 
$member_class->message;
     
     if(
$_POST['form_register']) {
         print 
'
         <h1>Register</H1>
         <form name="form1" method="post" action="">
             <table border="0">
              <tr>
                 <td width="100px;">username:</td>
              <td><input type="text" name="username" value="'
.$username.'"></td>
                 </tr>
                 <tr>
                  <td>password:</td>
              <td><input type="password" name="password" value="'
.$password.'"></td>
                 </tr>
                 <tr>
                  <td colspan="2">
                  <input type="hidden" name="register" value="true">
                  <input name="remember" type="checkbox" id="remember" value="1"> remember me for 2 weeks
                  </td>
                 </tr>
                 <tr>
                   <td colspan="2" height="20px" valign="bottom" align="right"><input type="submit" name="Register" value="Register"></td>
                 </tr>
             </table>
         </form>'
;
  
     }
     elseif(!
$_SESSION['username'])   {
      print 
'
      <h1>Login</H1>
      <form name="form1" method="post" action="">
             <table border="0">
              <tr>
              <td colspan="2" align="right"><input type="submit" name="form_register" value="register" style="border: 0px; background: transparant; text-decoration: underline; cursor: pointer;"></td>
              </tr>
              <tr>
                 <td width="100px">username:</td>
              <td><input type="text" name="username" value="'
.$username.'"></td>
              </tr>
              <tr>
                  <td>password</td>
              <td><input type="password" name="password" value="'
.$password.'"></td>
              </tr>
              <tr>
                  <td colspan="2">
                  <input name="remember" type="checkbox" id="remember" value="1"> remember me for 2 weeks
                  </td>
              </tr>
              <tr>
              <td colspan="2" height="20px" valign="bottom" align="right"><input type="submit" name="Login" value="Login"></td>
              </tr>
          </table>
      </form>'
;
     }elseif(
$_SESSION['username'])   {
         echo 
'<p>'.$_SESSION['username'].', you\'re logged on</p>';
         print 
'
         <form name="form1" method="post" action="">
             <input type="submit" name="Logout" value="Logout">
         </form>'
;
     }
  
?>


the db_connect.php file just makes a connection with the mysql database

PHP Code:
<?php
  
/**
   * Connect to the mysql database.
   */
  
$conn mysql_connect("localhost""username""password") or die(mysql_error());
  
mysql_select_db('database'$conn) or die(mysql_error());
  
?>

Reply With Quote
  #15  
Old April 14th, 2005, 02:36 AM
dejaone dejaone is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Feb 2005
Posts: 34 dejaone User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 47 m 11 sec
Reputation Power: 14
I'm working on a login script. The code example is definitely helpful.

Reply With Quote
  #16  
Old May 21st, 2005, 04:14 AM
M()()SE M()()SE is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2005
Posts: 1 M()()SE User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 18 m 31 sec
Reputation Power: 0
This is great

I love the fact that this code just worked, first time, no problems. As I'm still learning, it can take me a long time to go through and figure out what part isnt working with my particular setup.

Thanks to everyone who worked on this code

M()()SE

Reply With Quote
  #17  
Old July 19th, 2005, 11:11 AM
guidoeffe guidoeffe is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jul 2005
Posts: 1 guidoeffe User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 13 m 39 sec
Reputation Power: 0
Very nice script!!!

For you, witch parameter is the most secure to use as condition to show the reserved area?

One of the session parameters like $_SESSION['username'] or cookie?

I try also to insert a level condition...

Thanks for all....


bye.

Reply With Quote
  #18  
Old September 16th, 2005, 12:14 AM
Oscillate Oscillate is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Sep 2005
Posts: 1 Oscillate User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 44 m 2 sec
Reputation Power: 0
Small error

I'm glad you posted that example, TallyHo, as the article itself was difficult for me to get something worthwhile out of - I'm a PHP beginner, having only coded for a year or so. Thanks also to you, Miseryshining; I copied your script because I'm not using PHPLIB. Kudos to Martin for writing the article of course. The above link doesn't work, click here if you want to read the article.

I just wanted to mention a small error I found. When you destroy the cookie in logout(), you assign the expiration time to the value parameter of the cookie, not to the expire parameter.

This:
PHP Code:
 setcookie('remember',time()-3600); 

Should be changed to
PHP Code:
 setcookie('remember'''time()-3600); 

I had a lot of problems with the unserialize function, and after failing to fix this I chose to replace it with the explode function. I read somewhere - I think at php.net, but when reference checking I couldn't find it again - that there are security concerns with serialize/unserialize and that implode/explode is safer.

To make the change, in update_cookie() replace
PHP Code:
 $cookie serialize(array($_SESSION['username'],$token)); 

with
PHP Code:
 $cookie implode("|", array($_SESSION['uid'],$token)); 

And in check_remembered() replace
PHP Code:
list($username,$token) = unserialize($serializedArray); 

with
PHP Code:
 $explode_cookie explode("|"$serializedArray);
$uid $explode_cookie[0] ? $explode_cookie[0] : '';
$token = (!empty($explode_cookie[1])) ? $explode_cookie[1] : ''

Notice that I've replaced the username with userid (uid) instead. This means that for the rest of the function replace every occurence of 'username' with 'uid'. This is because with the implode function the username would show plainly in the cookie. For some malicious high schooler sitting at a school computer browsing cookies, he could think, "hey, I know this guy, I'll steal his session". Just a small thing, really.

On to the next fix. This code in the check_remembered() function looks wrong to me (please correct me if I'm wrong).
PHP Code:
 $result mysql_fetch_array(mysql_query("SELECT * FROM member WHERE username = '{$username}' AND token ='{$token}' AND ip = '{$ip}'"), MYSQL_ASSOC) or DIE ($this->query_error);
if (!
$result)   {
$this->set_session($result,false,false);
}else{
$this->set_session($result,true,true);


Why the "or DIE()" part? Right after, the "or" part is dealt with in the if (!$result) statement. When there's no result, the "or DIE()" part was triggered so the if (!$result) statement was never run.

Thinking of it now, my problems might all have occured only because of the setcookie error described in the beginning of the post. The script tried to unserialize the unix timestamp that was the cookie value, which didn't work. That again led to problems later with getting the result from the query, and I realize the "or DIE()" part is for when the query fails - not when not finding a result but when failing to run. Anyway, I will let my post stand as it is, with a recommendation to people to first change only the setcookie error and see if that works. (Bolded for people who don't read posts carefully .) If serialize/unserialize still doesn't work, swap it with implode/explode.


For those who want it easy, I'll quickly sum up my finished code:

logout():
PHP Code:
function logout()   {
             
// blowup cookie
             
setcookie('remember'''time()-3600);
             
$this->set_session_defaults();
         } 


update_cookie():
PHP Code:
function update_cookie($token)   {
             
$cookie implode("|", array($_SESSION['uid'],$token));
             
setcookie('remember',$cookietime()+12099600);
         } 


check_remembered():
PHP Code:
function check_remembered($cookie)   {
     
             
$serializedArray=$cookie;
             
$serializedArray stripslashes($serializedArray);
             
$explode_cookie explode("|"$serializedArray);
             
$uid $explode_cookie[0] ? $explode_cookie[0] : '';
             
$token = (!empty($explode_cookie[1])) ? $explode_cookie[1] : '';
     
             if(empty(
$uid) or empty($token))   {
                 return;
             } else {
                 
$uid mysql_escape_string($uid);
                 
$token mysql_escape_string($token);
                 
$ip mysql_escape_string($_SERVER['REMOTE_ADDR']);
             
$result mysql_fetch_array(mysql_query("SELECT * FROM member WHERE uid = '{$uid}' AND token ='{$token}' AND ip = '{$ip}'"), MYSQL_ASSOC);
     
                 if (!
$result)   {
                     
$this->set_session($result,false,false);
                 }else{
                     
$this->set_session($result,true,true);
                 }
             }
         } 


I have a question too. How do you use variables in the class that are from outside the class? Specifically, I have a config file with all my table names and I want to use them in the class.

That's it for now! Hopefully this will be helpful for anyone looking to use this script

Reply With Quote
  #19  
Old August 18th, 2007, 10:38 PM
OrangeJuiced OrangeJuiced is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Aug 2007
Posts: 1 OrangeJuiced User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 15 m 10 sec
Reputation Power: 0
Hello all,

My first post here and it looks like i'm ressurecting a very old post!

I am relatively new to php and have been looking for a secure log-in script and this seems to fit the bill...

Just wondering whether others with more experience could tell me how secure this is, 3 years after it was originally written!

It is working, for me, although i have a header conflict somewhere, but it is to late to mess with that tonight. Just wanted some comments so that i could muse over the possibility of using this on my site.

Thank you to all the posters above for your contributions to the original article (which I Googled). Very enlightening.

Regards

OJ

Reply With Quote
Reply

Viewing: Dev Articles Community ForumsProgrammingProgramming Tools > Article Dicussion: Creating a Secure PHP Login Script


Developer Shed Advertisers and Affiliates


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2018, Jelsoft Enterprises Ltd.

© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap