943,512 Members | Top Members by Rank

Ad:
  • PHP Discussion Thread
  • Marked Solved
  • Views: 2645
  • PHP RSS
You are currently viewing page 1 of this multi-page discussion thread
Aug 17th, 2009
0

Login System

Expand Post »
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
Similar Threads
Reputation Points: 462
Solved Threads: 392
Senior Poster
evstevemd is offline Offline
3,681 posts
since Jun 2007
Aug 17th, 2009
3

Re: Login System

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

PHP Syntax (Toggle Plain Text)
  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

PHP Syntax (Toggle Plain Text)
  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.

PHP Syntax (Toggle Plain Text)
  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

PHP Syntax (Toggle Plain Text)
  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.

PHP Syntax (Toggle Plain Text)
  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.

PHP Syntax (Toggle Plain Text)
  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

PHP Syntax (Toggle Plain Text)
  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.
Reputation Points: 235
Solved Threads: 193
Nearly a Posting Virtuoso
kkeith29 is offline Offline
1,315 posts
since Jun 2007
Aug 17th, 2009
0

Re: Login System

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/
Reputation Points: 12
Solved Threads: 32
Posting Whiz in Training
phpbeginners is offline Offline
226 posts
since Jul 2009
Aug 18th, 2009
0

Re: Login System

above code looks nice. try it
Reputation Points: 16
Solved Threads: 48
Posting Whiz
BzzBee is offline Offline
327 posts
since Apr 2009
Aug 21st, 2009
0

Re: Login System

Thanks alot KKeith29,
I failed to add to you some reputation points. I wonder why. That option isn't there in your username
Bravo!
Reputation Points: 462
Solved Threads: 392
Senior Poster
evstevemd is offline Offline
3,681 posts
since Jun 2007
Oct 12th, 2009
0
Re: Login System
does the above code prevents multiple login
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
j_limboo is offline Offline
70 posts
since Sep 2009
Oct 12th, 2009
0
Re: Login System
No. It can though. It wouldn't be hard to add.
Reputation Points: 235
Solved Threads: 193
Nearly a Posting Virtuoso
kkeith29 is offline Offline
1,315 posts
since Jun 2007
Oct 12th, 2009
0
Re: Login System
what lines and tables need to be added to prevent multiple logins
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
j_limboo is offline Offline
70 posts
since Sep 2009
Oct 12th, 2009
0
Re: Login System
lets take this code to the next level
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
j_limboo is offline Offline
70 posts
since Sep 2009
Nov 23rd, 2009
0
Re: Login System
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:
PHP Syntax (Toggle Plain Text)
  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
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
futhonguy is offline Offline
69 posts
since Oct 2009

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in PHP Forum Timeline: num_rows Faster than Counter?
Next Thread in PHP Forum Timeline: Send and receive sms





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC