Page 1 of 2 12 LastLast
Results 1 to 10 of 16
  1. #1
    Join Date
    Oct 2007
    Posts
    824
    Tokens
    71

    Latest Awards:

    Default [TUT] PHP Usersystem - Part 1

    I know this thread will end up in me being flamed but tuts have always helped me so I've decided to share. I know the code is horrible and inefficient but it's a tutorial. Also, the code loses it's formatting when I post it here so don't blame me.

    Lets start with the heart of the usersystem, the configuration file.
    config.php
    PHP Code:
    <?php
    // Defines the database information. Change to your own info.
    define('DB_USER','');
    define('DB_PASS','');
    define('DB_NAME','');
     
    // Connects to the database.
    $conn mysql_connect('localhost',DB_USER,DB_PASS);
    $select mysql_select_db(DB_NAME,$conn);
     
    // This function creates a hash instead of storing passwords plaintext. Change abc to anything you want
    function encrypt($str) {
     
    $str crypt(trim($str,'abc'));
     return 
    $str;
    }
     
    // This function strips input of any tags or special characters.
    function clean($str) {
     
    $str trim($str);
     if(!
    mysql_real_escape_string()) {
         
    $str addslashes($str);
        }
     
    $str strip_tags(htmlspecialchars($str));
     return 
    $str

     
    // Checks to see if user is logged in. 
    if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
     
    $query mysql_query("SELECT password FROM users WHERE username = '{$_SESSION['username']}'");
     if(!
    $query || mysql_num_rows($query) < 1) {
      unset(
    $_SESSION['username']);
      unset(
    $_SESSION['password']);
      
    $loggedin false;
     } else {
      
    $loggedin true;
     }
    } else {
     
    $loggedin false;
    }
     
    // Gets an array with the user's information in it.
    $query mysql_query("SELECT * FROM users WHERE username = '{$_SESSION['username']}'");
    $users mysql_fetch_array($query);
    ?>
    Now let's add a way for users to register.
    register.php
    PHP Code:
    <?php
    session_start
    ();
     
    // Loads the config file so we can use some stuff from it.
    require_once 'config.php';
     
    // Checks to see if the user is already logged in.
    if($loggedin) {
     die(
    'You are already logged in.');
    }
     
    // If the user hasn't submitted the form
    if(empty($_POST['register']) === false) {
    // Create an array to store errors
     
    $errors = array();
     
    // Cleans the input and ecnrypts the password
     
    $username clean($_POST['username']);
     
    $password encrypt($_POST['password']);
     
    // If they left a field empty
     
    if(!$_POST['username'] || !$_POST['password']) {
      
    $errors[] = 'You left a field blank';
     }
     
    // If the username they entered is longer than 30 characters.
     
    if(strlen($username) > 30) {
      
    $errors[] = 'Your username cannot exceed 30 characters.';
     }
     
    // Checks to see if the username is in the database
     
    $query mysql_query("SELECT username FROM users WHERE username = '$username'");
     
    $count mysql_num_rows($query);
     
    // If the username is in the database, error them
     
    if($count ) {
      
    $errors[] = 'That username is already taken. Please choose another one.';
     }
     
    // Echos the errors.
     
    if($errors) {
      foreach(
    $errors as $disperrors) {
       echo 
    $disperrors.'<br />';
      }
      echo 
    'Click <a href="register.php">here</a> to go back.'
      
    die();
     }
     
    // If there are no errors, we can now add them to the database.
     
    $query mysql_query("INSERT INTO users (username , password) VALUES('$username' , '$password')");
     
    // Success message
     
    echo 'You have successfully registered, '.$username.'! You may now <a href="login.php">login</a>.';
     
    // If they haven't submitted the form
    } else {
     echo 
    '
     <form method="post" action="">
     Username: <br />
     <input type="text" maxlength="30" name="username" /> <br /> <br />
     Password: <br />
     <input type="password" maxlength="30" name="password" /> <br /> <br />
     <input type="submit" value="Register" name="register" />
     </form>
     '
    ;
    }
    ?>
    Now lets add the login part.
    login.php
    PHP Code:
    <?php
    session_start
    ();
     
    // Loads the config file
    require_once 'config.php';
     
    // If the user is already logged them stop them from viewing the page.
    if($loggedin) {
     die(
    'You are already logged in.');
    }
     
    // If they have submitted the form
    if(empty($_POST['login']) === false) {
    // Clean input and encrypt password
     
    $username clean($_POST['username']);
     
    $password encrypt($_POST['password']);
     
    // If they left a field blank
     
    if(!$_POST['username'] || !$_POST['password']) {
      
    $errors[] = 'You left a field blank.';
     }
     
    // Checks to see if the username and password match.
     
    $query mysql_query("SELECT password FROM users WHERE username = '$username'");
     
    // If the username doesn't exist, error them
     
    if(!$query || mysql_num_rows($query) < 1) {
      
    $errors[] = 'Username does not exist.';
     }
     
    // If the username/password is wrong, error them.
     
    $login mysql_fetch_array($query);
     
     if(
    $password != $login['password']) {
      
    $errors[] = 'Wrong username/password.';
     }
     
    // If there are any errors, echo them.
    if($errors) {
      foreach(
    $errors as $disperrors) {
       echo 
    $disperrors.'<br />';
      }
      echo 
    'Click <a href="login.php">here</a> to go back.'
      
    die();
     }
     
    // Add the username and password to the session
     
    $_SESSION['username'] = $username;
     
    $_SESSION['password'] = $password
     
    // Success message if there are no errors.
     
    echo 'Thanks for logging in. <a href="index.php">Main page</a>.';
     
    // Otherwise echo form
    } else {
     echo 
    '
     <form method="post" action=""> 
     Username: <br />
     <input type="text" name="username" /> <br /> <br />
     Password: <br />
     <input type="password" name="password" /> <br /> <br />
     <input type="submit" value="Login" name="login" />
     </form>
     '
    ;
    }
    ?>
    We also need a way to logout.
    logout.php
    PHP Code:
    <?php
    session_start
    ();
     
    // Load configuration
    require_once 'config.php';
     
    // If the user isn't logged in, they can't logout.
    if(!$loggedin) {
     die(
    'You need to be logged in to logout.');
    } else {
     
    // Gets rid of the session information
     
    unset($_SESSION['username']);
        unset(
    $_SESSION['password']);
        
    $_SESSION = array();
        
    session_destroy();
        
    // Lets them know they logged out.
        
    echo 'You have successfully logged out.';
    }
    ?>
    And finally, you need the database info.
    Code:
    CREATE TABLE users (
     id int(10) NOT NULL auto_increment primary key,
        username varchar(30) NOT NULL,
        password varchar(100) NOT NULL
    );
    To check if the user is logged in, use this:
    PHP Code:
    if($loggedin) {
    echo 
    'You are logged in!';

    Vouches
    [x][x]

  2. #2
    Join Date
    Nov 2008
    Posts
    194
    Tokens
    0

    Default

    Nice, might come in handy.

  3. #3
    Join Date
    May 2005
    Location
    San Francisco, CA
    Posts
    7,160
    Tokens
    2,331

    Latest Awards:

    Default

    First thing I've noticed straight away:

    PHP Code:
    $str crypt(trim($str,'abc')); 
    should be
    PHP Code:
    $str crypt(trim($str),'abc'); 
    (in the config.php file).

    Also, you're not kidding about the inefficiency, this code code could be shortened a lot and could also work a lot faster.
    Last edited by Invent; 17-04-2009 at 01:58 AM.

  4. #4
    Join Date
    Apr 2008
    Location
    Derby
    Posts
    4,668
    Tokens
    262

    Latest Awards:

    Default

    Im sure that using

    PHP Code:
    session_destroy(); 
    Is more than enough, instead of using
    unset and all that lot?


    And why would you need to start a session on the register form :S
    !
    Im still learning, so these arent slating your things , there for my own personal gain of knowledge!
    Back for a while

  5. #5
    Join Date
    Jun 2008
    Location
    West midlands, Birmingham.
    Posts
    2,093
    Tokens
    219

    Latest Awards:


  6. #6
    Join Date
    Apr 2008
    Location
    Derby
    Posts
    4,668
    Tokens
    262

    Latest Awards:

    Default

    sure you coiuld just use

    $passecrpyt = md5($password);

    To save all the

    function encrypt($str) {
    $str = crypt(trim($str,'abc'
    ));
    return
    $str
    ;
    }


    that you did?

    Back for a while

  7. #7
    Join Date
    Jun 2008
    Location
    West midlands, Birmingham.
    Posts
    2,093
    Tokens
    219

    Latest Awards:

    Default

    Quote Originally Posted by Obulus View Post
    sure you coiuld just use

    $passecrpyt = md5($password);

    To save all the

    function encrypt($str) {
    $str = crypt(trim($str,'abc'
    ));
    return
    $str
    ;
    }


    that you did?
    Does it really matter?

  8. #8
    Join Date
    Oct 2006
    Location
    London
    Posts
    342
    Tokens
    0

    Default

    My first reply in like a year lol!
    Code:
    // Connects to the database.$conn = mysql_connect('localhost',DB_USER,DB_PASS);$select = mysql_select_db(DB_NAME,$conn);
    1. why localhost? not always the case, why not define DB_HOST??

    2. make a file called functions_and_classes.php and require it!

    3. Don't select *. Don't store password (even if it's encrypted) as variables ($_SESSION super).

    4. Instead of $_SESSION, why not use DB sessions?

    5. Contradiction on #4 but use $_SESSION['logoutKey']. Not needed here but it's standard practices. what it is is a randomly assigned key on login which is checked when the user logs out to ensure that it is not a robot or noob longing them out.

    Great that people like you do this, it's the best way to teach people so +rep coming your way! (not sure what effect it'll have though!)

  9. #9
    Join Date
    May 2005
    Location
    San Francisco, CA
    Posts
    7,160
    Tokens
    2,331

    Latest Awards:

    Default

    4. Instead of $_SESSION, why not use DB sessions?
    Where's the need in that?

  10. #10
    Join Date
    Oct 2007
    Posts
    824
    Tokens
    71

    Latest Awards:

    Default

    Quote Originally Posted by Invent View Post
    First thing I've noticed straight away:

    PHP Code:
    $str crypt(trim($str,'abc')); 
    should be
    PHP Code:
    $str crypt(trim($str),'abc'); 
    (in the config.php file).

    Also, you're not kidding about the inefficiency, this code code could be shortened a lot and could also work a lot faster.
    Oh sorry, that was a typo. Must have accidentally erased it when I was changing the salt. I'll fix it.

    Quote Originally Posted by Obulus View Post
    Im sure that using

    PHP Code:
    session_destroy(); 
    Is more than enough, instead of using
    unset and all that lot?


    And why would you need to start a session on the register form :S
    !
    Im still learning, so these arent slating your things , there for my own personal gain of knowledge!
    I'm not sure about the session_destroy. And you're right about the register, I'll take it out.

    Quote Originally Posted by Obulus View Post
    sure you coiuld just use

    $passecrpyt = md5($password);

    To save all the

    function encrypt($str) {
    $str = crypt(trim($str,'abc'));
    return $str;
    }

    that you did?
    I'm pretty sure mine is harder to crack.

    Quote Originally Posted by Tabo View Post
    My first reply in like a year lol!
    Code:
    // Connects to the database.$conn = mysql_connect('localhost',DB_USER,DB_PASS);$select = mysql_select_db(DB_NAME,$conn);
    1. why localhost? not always the case, why not define DB_HOST??

    2. make a file called functions_and_classes.php and require it!

    3. Don't select *. Don't store password (even if it's encrypted) as variables ($_SESSION super).

    4. Instead of $_SESSION, why not use DB sessions?

    5. Contradiction on #4 but use $_SESSION['logoutKey']. Not needed here but it's standard practices. what it is is a randomly assigned key on login which is checked when the user logs out to ensure that it is not a robot or noob longing them out.

    Great that people like you do this, it's the best way to teach people so +rep coming your way! (not sure what effect it'll have though!)
    1. Most of the time, it's localhost
    2. I don't use any classes and theres only 2 functions anyways
    3. Why not select *?
    Vouches
    [x][x]

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •