Login System

Thread Solved

Join Date: Jun 2007
Posts: 1,474
Reputation: evstevemd has a spectacular aura about evstevemd has a spectacular aura about evstevemd has a spectacular aura about 
Solved Threads: 128
evstevemd's Avatar
evstevemd evstevemd is offline Offline
Nearly a Posting Virtuoso

Login System

 
0
  #1
Aug 17th, 2009
Hello All,
I want to make a CD/DVD Library where by an admin can do all the operations while any other norma user can do limited operations (simply browsing and searching). I'm still organizing and doing simple design and I need your opinions on this:
1. What is the best login technique (after storing users and passwords in database?). I can get usernames from database as well as from login forms but I'm not sure how to implement comparison the best way!

2. What is the best way of storing password? (secure way)

3. How do I redirect them to the right page after successful login

4. How do I prevent any unlogged user from accessing the Library script

Any answer to any question is appreciated
Atheist: God is man made imagination, he doesn't exist!
Theist: It's okay, can you imagine anything else that doesn't exist?
---- Python, C++ PHP and Java ----
Reply With Quote Quick reply to this message  
Join Date: Jun 2007
Posts: 1,227
Reputation: kkeith29 has a spectacular aura about kkeith29 has a spectacular aura about kkeith29 has a spectacular aura about 
Solved Threads: 167
kkeith29's Avatar
kkeith29 kkeith29 is offline Offline
Nearly a Posting Virtuoso

Re: Login System

 
2
  #2
Aug 17th, 2009
Here is something I typed up a while ago. Its a complete login and registration system. Just create the following pages and create the database and tables. After that it should work.

This system is safe from sql injection, spam bots, and cross-site request forgery. It doesn't have any xss holes.

PHP/MYSQL USER REGISTRATION AND LOGIN EXAMPLE

Database table
-------------------------------------------------------------
Todo - Create this table in your database

  1. CREATE TABLE `login` (
  2. `id` INT NOT NULL AUTO_INCREMENT ,
  3. `username` VARCHAR( 30 ) NOT NULL ,
  4. `password` VARCHAR( 100 ) NOT NULL ,
  5. PRIMARY KEY ( `id` ) ,
  6. UNIQUE ( `username` )
  7. ) ENGINE = MYISAM

Database connection page - includes/dbconnect.php
-------------------------------------------------------------
Description - Holds database connection. This is used to get rid of redundant code in each page. It also helps if you change your username/password/database name you won't have to update every page, just one.
Todo - Fill the variables with the proper information

  1. <?php
  2.  
  3. $host = 'localhost';
  4. $user = '';
  5. $pass = '';
  6. $dbname = '';
  7.  
  8. $con = mysql_connect( $host,$user,$pass ) or die('Unable to connect');
  9. mysql_select_db( $dbname ) or die('Unable to select database');
  10.  
  11. ?>

Functions page - includes/functions.php
-------------------------------------------------------------
Description - Holds the functions. Used so you don't have to repeat the functions in each page. Also, if you need to update a function, you only will have to do it once.

  1. <?php
  2.  
  3. function encryptPassword( $pass,$salt=false,$saltLength=4 ) {
  4. if ( $salt === false ) {
  5. $res = '';
  6. for( $i=0;$i<$saltLength;$i++ ) {
  7. $res .= pack( 's',mt_rand() );
  8. }
  9. $salt = substr( base64_encode( $res ),0,$saltLength );
  10. }
  11. return $salt . sha1( $salt . $pass );
  12. }
  13.  
  14. function checkPassword( $pass,$hash,$saltLength=4 ) {
  15. if ( encryptPassword( $pass,substr( $hash,0,$saltLength ) ) === $hash ) {
  16. return true;
  17. }
  18. return false;
  19. }
  20.  
  21. ?>

Registration page - register.php
-------------------------------------------------------------
Description - Gets username and password from user, validates them, and inserts into database

  1. <?php
  2.  
  3. session_start();
  4.  
  5. require('includes/functions.php'); //include functions
  6. require('includes/dbconnect.php'); //include db connection
  7.  
  8. $min_form_time = 5; //in seconds
  9. $max_form_time = 30; //in seconds
  10.  
  11. $error = array(); //define $error to prevent error later in script
  12. $message = '';
  13. if ( isset( $_POST['submit'] ) ) {
  14. $error = array();
  15. array_map( 'stripslashes',&$_POST ); //Strips slashes
  16. array_map( 'mysql_real_escape_string',&$_POST ); //Escapes data to protect against sql injection
  17. $user = $_POST['username'];
  18. $pass = $_POST['password'];
  19. $token = $_POST['token'];
  20. if ( $token !== $_SESSION['token'] ) {
  21. $error[] = 'Token is invalid';
  22. }
  23. else {
  24. if ( time() <= ( $_SESSION['time'] + $min_form_time ) ) {
  25. $error[] = 'Form submitted too quickly, please slow down and try again';
  26. }
  27. elseif ( time() >= ( $_SESSION['time'] + $max_form_time ) ) {
  28. $error[] = 'Form has expired';
  29. }
  30. else {
  31. if ( empty( $user ) ) { //check if username is blank
  32. $error[] = 'Username is blank';
  33. }
  34. elseif ( strlen( $user ) > 30 ) { //make sure the username is not longer than 30 chars
  35. $error[] = 'Username is longer than 30 characters';
  36. }
  37. else { //if there aren't any errors with $user at this point, check to make sure no one else has the same username
  38. $query = mysql_query( "SELECT * FROM `login` WHERE `username` = '{$user}'",$con );
  39. if ( mysql_num_rows( $query ) > 0 ) {
  40. $error[] = 'Username already exists';
  41. }
  42. }
  43. if ( empty( $pass ) ) { //check if password is blank
  44. $error[] = 'Password is blank';
  45. }
  46. elseif ( strlen( $pass ) < 9 ) { //make sure password is longer than 8 characters
  47. $error[] = 'Password must be longer than 8 characters';
  48. }
  49. elseif ( !preg_match( "/^.*(?=.{3,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/",$pass ) ) { //check to see if its a valid password
  50. $error[] = 'Password invalid - it must contain at least 1 number, 1 uppercase letter, 1 lowercase letter';
  51. }
  52. if ( count( $error ) == 0 ) { //if there are no errors, then insert into database
  53. $pass = encryptPassword( $pass ); //hash password before inserting into database
  54. $query = mysql_query( "INSERT INTO `login` (`username`,`password`) VALUES ('{$user}','{$pass}')",$con );
  55. $message = 'User registration successful!';
  56. }
  57. }
  58. }
  59. }
  60.  
  61. $errmsg = '';
  62. if ( count( $error ) > 0 ) { //if there are errors, build the error list to be displayed.
  63. $errmsg = '<div>Errors:<br /><ul>';
  64. foreach( $error as $err ) { //loop through errors and put then in the list
  65. $errmsg .= "<li>{$err}</li>";
  66. }
  67. $errmsg .= '</ul></div>';
  68. }
  69.  
  70. $token = md5(uniqid(rand(),true));
  71. $_SESSION['token'] = $token;
  72. $_SESSION['time'] = time();
  73.  
  74. $html =<<<HTML
  75. <html>
  76. <head>
  77. <title>Registration</title>
  78. </head>
  79. <body>
  80. <h3>Member Registration</h3>
  81. {$errmsg}
  82. <div>
  83. <form action="{$_SERVER['PHP_SELF']}" method="post">
  84. Username: <input type="text" name="username" /><br />
  85. Password: <input type="password" name="password" /><br />
  86. <input type="hidden" name="token" value="{$token}" />
  87. <input type="submit" name="submit" value="Register" />
  88. </form>
  89. </div>
  90. <div style="color:#ff0000">{$message}</div>
  91. </body>
  92. </html>
  93. HTML;
  94.  
  95. echo $html;
  96.  
  97. ?>

Login page - login.php
-------------------------------------------------------------
Description - Gets username and password from user, validates them, and check to see if user is present in database and sets a session.

  1. <?php
  2.  
  3. session_start(); //start session so we can login
  4.  
  5. require('includes/functions.php'); //include functions
  6. require('includes/dbconnect.php'); //include database connection
  7.  
  8. $min_form_time = 5; //in seconds
  9. $max_form_time = 30; //in seconds
  10.  
  11. $error = array(); //define $error to prevent error later in script.
  12. if ( isset( $_POST['submit'] ) ) {
  13. $error = array();
  14. array_map( 'stripslashes',&$_POST ); //Strips slashes
  15. array_map( 'mysql_real_escape_string',&$_POST ); //Escapes data to protect against sql injection
  16. $user = $_POST['username'];
  17. $pass = $_POST['password'];
  18. $token = $_POST['token'];
  19. if ( $token !== $_SESSION['token'] ) {
  20. $error[] = 'Token is invalid';
  21. }
  22. else {
  23. if ( time() <= ( $_SESSION['time'] + $min_form_time ) ) {
  24. $error[] = 'Form submitted too quickly, please slow down and try again';
  25. }
  26. elseif ( time() >= ( $_SESSION['time'] + $max_form_time ) ) {
  27. $error[] = 'Form has expired';
  28. }
  29. else {
  30. if ( empty( $user ) ) { //check if username is blank
  31. $error[] = 'Username is blank';
  32. }
  33. elseif ( strlen( $user ) > 30 ) { //make sure the username is not longer than 30 chars
  34. $error[] = 'Username is longer than 30 characters';
  35. }
  36. if ( empty( $pass ) ) { //check if password is blank
  37. $error[] = 'Password is blank';
  38. }
  39. elseif ( strlen( $pass ) < 9 ) { //make sure password is longer than 8 characters
  40. $error[] = 'Password must be longer than 8 characters';
  41. }
  42. elseif ( !preg_match( "/^.*(?=.{3,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/",$pass ) ) { //check to see if its a valid password
  43. $error[] = 'Password invalid - it must contain at least 1 number, 1 uppercase letter, 1 lowercase letter';
  44. }
  45. if ( count( $error ) == 0 ) { //if everything is ok so far, keep going (i do this because i don't want to hit the database if the username or password is blank)
  46. $query = mysql_query( "SELECT `id`,`password` FROM `login` WHERE `username` = '{$user}' LIMIT 1",$con );
  47. if ( mysql_num_rows( $query ) !== 1 ) { //checks to see if a row was found with username provided by user
  48. $error[] = 'Username and/or Password incorrect'; //never be specific with errors, makes it hard to crack
  49. }
  50. else {
  51. list( $id,$hash ) = mysql_fetch_row( $query ); //puts the id and password from result into $id and $pass variables
  52. if ( !checkPassword( $pass,$hash ) ) { //check password from user against the hash in the database.
  53. $error[] = 'Username and/or Password incorrect';
  54. }
  55. if ( count( $error ) == 0 ) { //if now errors found, then set session for login
  56. $_SESSION['auth'] = $id;
  57. header('Location: member.php'); //redirect to <strong class="highlight">secure</strong> area
  58. exit; //exit script since we are redirecting anyway
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }
  65.  
  66. $errmsg = '';
  67. if ( count( $error ) > 0 ) { //if there are errors, build the error list to be displayed.
  68. $errmsg = '<div>Errors:<br /><ul>';
  69. foreach( $error as $err ) { //loop through errors and put then in the list
  70. $errmsg .= "<li>{$err}</li>";
  71. }
  72. $errmsg .= '</ul></div>';
  73. }
  74.  
  75. $token = md5(uniqid(rand(),true));
  76. $_SESSION['token'] = $token;
  77. $_SESSION['time'] = time();
  78.  
  79. $html =<<<HTML
  80. <html>
  81. <head>
  82. <title>Login</title>
  83. </head>
  84. <body>
  85. <h3>Member Login</h3>
  86. {$errmsg}
  87. <div>
  88. <form action="{$_SERVER['PHP_SELF']}" method="post">
  89. Username: <input type="text" name="username" /><br />
  90. Password: <input type="password" name="password" /><br />
  91. <input type="hidden" name="token" value="{$token}" />
  92. <input type="submit" name="submit" value="Login" />
  93. </form>
  94. </div>
  95. </body>
  96. </html>
  97. HTML;
  98.  
  99. echo $html;
  100.  
  101. ?>

Member area - member.php
-------------------------------------------------------------
Description - place where people who are successfully logged in go. Information on this page is only for members to access, no one else can see it.

  1. <?php
  2.  
  3. session_start(); //start session so we can see if the user is logged in.
  4.  
  5. if ( !isset( $_SESSION['auth'] ) ) { // if auth is not in the $_SESSION array (meaning they haven't been to the login page where its set) redirect them to the login page
  6. header('Location: login.php');
  7. exit;
  8. }
  9.  
  10. require('includes/dbconnect.php'); //include database connection
  11.  
  12. $memid = $_SESSION['auth']; //set member id into $memid.
  13.  
  14. $query = mysql_query( "SELECT `username` FROM `login` WHERE `id` = {$memid}" ); //
  15. $member = mysql_fetch_assoc( $query );
  16.  
  17. echo "Welcome, {$member['username']} <a href=\"logout.php\">Logout</a>";
  18.  
  19. ?>

Logout page - logout.php
-------------------------------------------------------------
Description - logs out member and redirects to login page

  1. <?php
  2.  
  3. session_start(); //start session so we can logout
  4.  
  5. unset( $_SESSION['auth'] ); //remove auth from the $_SESSION array
  6.  
  7. header('Location: login.php');
  8. exit;
  9.  
  10. ?>
Last edited by kkeith29; Aug 17th, 2009 at 2:16 pm.
Google is your friend.

Use [code] tags.

If you have found a solution to your problem, please mark the thread as SOLVED.
Reply With Quote Quick reply to this message  
Join Date: Jul 2009
Posts: 128
Reputation: phpbeginners has a little shameless behaviour in the past 
Solved Threads: 16
phpbeginners phpbeginners is offline Offline
Junior Poster

Re: Login System

 
0
  #3
Aug 17th, 2009
Try this: http://evolt.org/node/60384
Admin/user

If you want multiple login with the number of cashier, supervisor etc...
Admin/master/agent/user/guest
http://sourceforge.net/projects/phploginsystemw/
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 257
Reputation: BzzBee is an unknown quantity at this point 
Solved Threads: 37
BzzBee BzzBee is offline Offline
Posting Whiz in Training

Re: Login System

 
0
  #4
Aug 18th, 2009
above code looks nice. try it
Reply With Quote Quick reply to this message  
Join Date: Jun 2007
Posts: 1,474
Reputation: evstevemd has a spectacular aura about evstevemd has a spectacular aura about evstevemd has a spectacular aura about 
Solved Threads: 128
evstevemd's Avatar
evstevemd evstevemd is offline Offline
Nearly a Posting Virtuoso

Re: Login System

 
0
  #5
Aug 21st, 2009
Thanks alot KKeith29,
I failed to add to you some reputation points. I wonder why. That option isn't there in your username
Bravo!
Atheist: God is man made imagination, he doesn't exist!
Theist: It's okay, can you imagine anything else that doesn't exist?
---- Python, C++ PHP and Java ----
Reply With Quote Quick reply to this message  
Join Date: Sep 2009
Posts: 70
Reputation: j_limboo is an unknown quantity at this point 
Solved Threads: 0
j_limboo j_limboo is offline Offline
Junior Poster in Training
 
0
  #6
Oct 12th, 2009
does the above code prevents multiple login
Reply With Quote Quick reply to this message  
Join Date: Jun 2007
Posts: 1,227
Reputation: kkeith29 has a spectacular aura about kkeith29 has a spectacular aura about kkeith29 has a spectacular aura about 
Solved Threads: 167
kkeith29's Avatar
kkeith29 kkeith29 is offline Offline
Nearly a Posting Virtuoso
 
0
  #7
Oct 12th, 2009
No. It can though. It wouldn't be hard to add.
Google is your friend.

Use [code] tags.

If you have found a solution to your problem, please mark the thread as SOLVED.
Reply With Quote Quick reply to this message  
Join Date: Sep 2009
Posts: 70
Reputation: j_limboo is an unknown quantity at this point 
Solved Threads: 0
j_limboo j_limboo is offline Offline
Junior Poster in Training
 
0
  #8
Oct 12th, 2009
what lines and tables need to be added to prevent multiple logins
Reply With Quote Quick reply to this message  
Join Date: Sep 2009
Posts: 70
Reputation: j_limboo is an unknown quantity at this point 
Solved Threads: 0
j_limboo j_limboo is offline Offline
Junior Poster in Training
 
0
  #9
Oct 12th, 2009
lets take this code to the next level
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 43
Reputation: futhonguy is an unknown quantity at this point 
Solved Threads: 0
futhonguy futhonguy is offline Offline
Light Poster
 
0
  #10
30 Days Ago
I tried to use the above code for an example and i came across a Deprecated on Call-time pass-by-reference for these following code:
  1. array_map( 'stripslashes',&$_POST ); //Strips slashes
  2. array_map( 'mysql_real_escape_string',&$_POST ); //Escapes data to protect against sql injection
.

can anyone assist me on this? thanks
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the PHP Forum


Views: 1421 | Replies: 13
Thread Tools Search this Thread



Tag cloud for PHP
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC