login script

Discussion in 'PHP' started by tastro, Mar 7, 2009.

  1. #1
    hi,

    i need a really "SECURE" login script that expires in 5min or 10min.
    also that you are logged out automaticlly after 5min if you don't logout
    manually. the script should be made as simple as possible.
    and the script must read username/password from a mysql database.

    i know that this shouldn't be such a big problem for you masters around here.
    i searched google a lot but couldn't find any good one. :S

    best regards, tastro
     
    tastro, Mar 7, 2009 IP
  2. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #2
    Barti1987, Mar 7, 2009 IP
  3. tastro

    tastro Member

    Messages:
    68
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    tnx m8, but i'm searching for one that is more simple... :S anyone ?
     
    tastro, Mar 8, 2009 IP
  4. Dennis M.

    Dennis M. Active Member

    Messages:
    119
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    58
    #4
    Sure, mind if I use sessions? Now I don't know your database structure so I made my own. Here goes:

    database.sql
    CREATE TABLE `users` (
    `id` BIGINT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `username` VARCHAR( 32 ) NOT NULL ,
    `password` VARCHAR( 32 ) NOT NULL ,
    `salt` VARCHAR( 10 ) NOT NULL
    ) ENGINE = MYISAM ;
    Code (markup):
    init.php
    <?php
    /**
     * Simple _SECURE_ login by Dennis McWherter
     *
     * This is a free script. Under no circumstances does anyone have permission
     * to sell this script!
     *
     * Nothing needs to be touched in this file. For everything to work, however,
     * this must be the first file included!
     *
     */
    session_start();
    
    // Now logout if idle for 5 minutes :) (300 seconds)
    if(isset($_SESSION['username'])){
      if(time() > $_SESSION['time']+300){
        session_destroy();
        exit;
       }
      $_SESSION['time'] = time(); // Passed the test, renew session time...
    }
    
    define("SCRIPT",true); // Define for script..
    
    // Any other definitions below...
    
    ?>
    PHP:
    functions.php
    <?php
    /**
     * Simple _SECURE_ login by Dennis McWherter
     *
     * This is a free script. Under no circumstances does anyone have permission
     * to sell this script!
     *
     * Login functions are in here :)
     *
     */
    if(!defined("SCRIPT")){
      print "Unauthorized access!";
      exit;
    }
    
    class Login_Base{
    
    	/**
    	 * Constructor...
    	 *
    	 */
    	function __construct(){
    		// MySQL info
    		mysql_connect("localhost","DBUSER","DBPASS");
    		mysql_select_db("DATABASE");
    	}
    
    	/**
    	 * The actual login function...
    	 *
    	 * Author: Dennis McWherter
    	 *
    	 */
    	function login($user,$pass){
    		// Grab the random salt...
    		$salt = mysql_query("SELECT `salt` FROM `users` WHERE username='".mysql_escape_string($user)."' LIMIT 1;");
    		if(mysql_num_rows($salt) == 0){
    			return false;
    		}
    		$salt = implode(mysql_fetch_row($salt));
    		// Now make the password :)
    		$pass = md5($salt.$pass.$salt); // Could do this a variety of ways really.. but yeah this works
    		unset($salt);
    		// User query
    		$query = mysql_query("SELECT * FROM `users` WHERE username='".mysql_escape_string($user)."' AND password='".mysql_escape_string($pass)."' LIMIT 1;");
    		if(mysql_num_rows($query) == 0){
    			return false;
    		}
    		unset($query);
    		// All seems to check out fine...
    		$_SESSION['username'] = $user;
    		$_SESSION['time']     = time();
    		return true;
    	}
    
    	/**
    	 * Register! :D
    	 *
    	 * Author: Dennis McWherter
    	 *
    	 */
    	function register($user,$pass){
    		// Run some checks...
    		$check = mysql_query("SELECT * FROM `users` WHERE username='".mysql_escape_string($user)."' LIMIT 1;");
    		if(mysql_num_rows($check) != 0){
    			return false;
    		}
    
    		// Every one loves salt... I'm addicted personally ;P
    		// We'll make.. hmm. a 10char salt! :)
    		$chars = "!a@b$g%^&*()_+=-'\";][\\/:87{}~`";
    
    		// Make the salt
    		for($i=0;$i<10;$i++){
    			$salt .= $chars[rand() % strlen($chars)-.07];
    		}
    
    		// Make the pass
    		$pass = md5($salt.$pass.$salt);
    
    		// Insert stuff into DB
    		if(mysql_query("INSERT INTO `users` (`id`,`username`,`password`,`salt`) VALUES (NULL, '".mysql_escape_string($user)."', '".$pass."', '".$salt."')")){
    			return true;
    		}
    		return false;
    	}			
    
    }
    
    ?>
    PHP:
    index.php
    <?php
    /**
     * Simple _SECURE_ login by Dennis McWherter
     *
     * This is a free script. Under no circumstances does anyone have permission
     * to sell this script!
     *
     */
    include_once("init.php"); // This will take care of starting our sessions and all prelim stuff
    include_once("functions.php"); // All our functions will just sit in here!
    
    // Define our function class
    $login = new Login_Base;
    
    // Well if the user isn't logged in then tell them to do so!
    if(!isset($_SESSION['username']) && $_GET['page'] != "register" && !isset($_POST['form'])){
      print "<form name=\"login\" method=\"post\" action=\"?page=login\">
    	<p>Username: <input type=\"text\" name=\"user\" /></p>
    	<p>Password: <input type=\"password\" name=\"pass\" /></p>
    	<p><input type=\"submit\" value=\"login\" /></p>
    	<input type=\"hidden\" name=\"form\" value=\"true\" />
    	</form>
    	<p><a href=\"?page=register\">Register Now!</a></p>";
      exit;
    }
    
    // Default everything out :)
    if(!isset($_GET['page'])){
      $_GET['page'] = "index";
    }
    
    switch(strtolower($_GET['page'])){
      default:
        print "<p>The login has been successful!<br /><br />
        Your username is: ".$_SESSION['username']."<br /><br />
        Please proceed with the following:<br />
        <a href=\"test.php\">Test page 2</a> (Separate page to show that it carries)<br />
        <a href=\"?page=logout\">Logout</a></p>";
      break;
      case 'logout':
        if(session_destroy()){
          print "Successfully logged out!";
          exit;
        } else {
          print "There was an error logging out!";
          exit;
        }
      break;
      case 'register':
        if($_GET['act'] != "go"){
          print "<form name=\"register\" method=\"post\" action=\"?page=register&act=go\">
    	     <p>Username: <input type=\"text\" name=\"user\" /></p>
    	     <p>Password: <input type=\"password\" name=\"pass\" /></p>
    	     <p><input type=\"submit\" value=\"Register\" /></p>
    	     </form>";
        } else {
          if($login->register($_POST['user'],$_POST['pass'])){
    	print "Registration successful! You can now login!";
          } else {
    	print "Registration failed!";
          }
        }
      break;
      case 'login':
        if($login->login($_POST['user'],$_POST['pass'])){
          print "Login successful! Please go back <a href=\"?page=index\">home</a>";
          exit;
        } else {
          print "Login failed!";
          exit;
        }
      break;
    }
    mysql_close();
    ?>
    PHP:
    test.php
    <?php
    /**
     * Simple _SECURE_ login by Dennis McWherter
     *
     * This is a free script. Under no circumstances does anyone have permission
     * to sell this script!
     *
     * Test script :D
     *
     */
    include_once("init.php");
    
    if(!isset($_SESSION['username'])){
      print "You're not logged in... <a href=\"index.php\">index</a>";
      exit;
    }
    
    print "Your username is still ".$_SESSION['username']." - success! :)<br /><br />
    <a href=\"index.php\">home</a>";
    
    ?>
    PHP:
    and that's all there is to it mate! Good luck! ;)

    Regards,
    Dennis M.
     
    Dennis M., Mar 8, 2009 IP
  5. tastro

    tastro Member

    Messages:
    68
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #5
    that a really nice one, thx m8 :p
    btw... are sessions bad ?
    u need them anyways if you want that the user can stay logged in and view other pages right ?
    or is there some other way too ?
     
    tastro, Mar 10, 2009 IP
  6. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #6
    They're not good or bad, they're a tool. If you use them for an appropriate purpose then they're useful.

    Handling a login like this is an appropriate purpose. To do it any other way you'd end up re-creating the functionality of sessions anyway.
     
    SmallPotatoes, Mar 10, 2009 IP