[PHP+SQL] User Database in under 5 min. [Tut]

Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,098Posts

    [PHP+SQL] User Database in under 5 min. [Tut]

    Basicly you only need 3 things for a secure user database.
    • You need the register form.
    • You need the login form.
    • You need the database.
    So here's how it works. (simpled down of corse)

    Start with the register form. (register.php)

    Put this code in the head of the PHP page.
    PHP Code:
    <?php
    //If user submitted the form and entered greater than $max and less than $min characters.
    $max 12//Max is set to 12.
    $min 3//Min is set to 3.
    if( strlen($_POST['user']) >= ($min) && strlen($_POST['user']) <= ($max) ) {
      
    $user=$_POST['user'];
      
    $pass=$_POST['pass'];
      
    $pass2=$_POST['pass2'];
     
      
    //If passwords don't match, record error and display message.
      
    if($pass != $pass2) {
        echo (
    '<p>passwords do not match.<br> <a href="'.$_SERVER['HTTP_REFERER'].'">Try Again</a> </p>');
     
        if(
    strlen($bad)<1) {
           
    $bad=1;
        } else {
            
    $bad+=1;
        }
     
     }
     
     if(
    strlen($bad)<1) {
        include(
    'connect.php');
     
       
    // Perform the encryption (leaving first 2 letters of pass the same)
       
    $salt substr($_POST['pass'], 02);
       
    $pass crypt($_POST['pass'], $salt);
     
        
    $insert='INSERT INTO `users` (`user`,`pass`) VALUES("'.$user.'", "'.$pass.'")';
        
    $sql=mysql_query($insert) or die(mysql_error());
        echo (
    'User: '.$user.'<br>Pass: '.$pass.'<br> Created!');
        echo(
    '<meta http-equiv="refresh" content="5;URL=login.php" />');
        echo(
    '<p><a href="login.php">Refreshing in 5 seconds..</a></p>');
      }
    }
    ?>
    Put this code in the body of the PHP page.
    Code:
    <form name="regi" id="regi" action="register.php" method="post" />
    <p>
      <strong>Username: </strong>
      <input type="text" name="user" id="user" value="<?=$user?>" />
      <br>
      <strong>Password: </strong>
      <input type="password" name="pass" id="pass"  value="<?=$pass?>" />
      <br>
      <strong>Repeat Pass:</strong> 
      <input type="password" name="pass2" id="pass2"  value="<?=$pass2?>" />
      <br>
      <input type="submit" name="submit" id="submit" value="Submit" />
      </form>
    </p>









    That's a registration form.
    1. We found out if the user submitted the form.
    2. When they do, check to see if passwords match.
    3. If there are no errors, encrypt the pass, and add data to database.
    Now, before any of this will work, you need a connect page. (connect.php)
    PHP Code:
    <?php
    // --------------------------- Edit SQL Connect Info --------------------------- //
    $sql_host "host";
    $sql_user "user";
    $sql_pass "pass";
    $sql_database "database";
    // ------------------------- DO NOT EDIT BELOW THIS LINE ---------------------------- //
     
    $db mysql_connect($sql_host$sql_user$sql_pass) or die("Could not connect.");
    if(!
    $db
     die(
    "no db");
    if(!
    mysql_select_db($sql_database,$db))
      die(
    "No database selected.");
     
    ?>
    Put your mysql database information where you see "host", etc..







    Before that will work, you need a database to put everything.




    EDIT: Click here to see the alternative.
    1. Open PhpMyAdmin. Create a table called users with 3 fields(columns,rows)
    2. first field name: ID type: BIGINT extra: auto-increment Set to: Primary Key.
    3. second field name: user type: VARCHAR length: 45 Set to: Unique.
    4. third field name: pass type: text
    5. Save.
    Now your register page should work.

    Finally you need the login page (login.php)

    Put this at the very start of your page:
    PHP Code:
    <?php 
     
    session_start
    (); 
     
    //You can log users out with a link to this: login.php?logout=AnyTextHere
    if(strlen($_REQUEST['logout'])>0) {
      
    session_destroy();
      echo(
    '<meta http-equiv="refresh" content="1;URL=login.php" />');
      echo(
    '<p>Logged out.<br><a href="login.php">Refreshing in 1 second..</a></p>');
    }
    ?>
    • This needs to be above the <html> tag, and everything else.
    • The purpose of the session_start() is to let the page know that it needs to look for session varriables.
    • The purpose of the conditional statement there, is to log users out after they click a logout link or button.
    Put this at the head of your page:
    PHP Code:
    <?php
    if(!isset($_SESSION['user'])) {
      if(isset(
    $_POST['submit'])) {
        include(
    "connect.php");
        
    // Perform the encryption (leaving first 2 letters of pass the same)
        
    $salt substr($_POST['pass'], 02);
        
    $pass crypt($_POST['pass'], $salt);
     
        
    //Load user details from SQL Database
        
    $userSelect 'SELECT * FROM `users` WHERE `user` = "'.$_POST['user'].'" AND `pass` = "'.$pass.'" LIMIT 1';
        
    $userQuery mysql_query($userSelect) or die("Can not find ".$_POST['user']."<br><a href='".$_SERVER['HTTP_REFERER']."'>Try Again</a>");
        while(
    $userRow=mysql_fetch_array($userQuery)) {
     
           
    //Define Session Variables
           
    $_SESSION['user'] = $userRow['user'];
           
    $_SESSION['pass'] = $userRow['pass'];
           
    $_SESSION['ID'] = $userRow['ID'];
        }
      }
    }
    ?>
    • The above part gets the data for the logged in user. It gets them from the database, puts them in a session, and they will later be displayed on the page in the body.
    • If the form is not submitted, it does nothing.
    Put this in the body:
    PHP Code:
    <?php
     
    if(isset($_SESSION['user'])) {
       print 
    '<h1>Hello, <strong>'.$_SESSION['user'].'</strong></h1>';
       print 
    '<p>You are now logged in.';
       print 
    '<br>Your ID is: <strong>'.$_SESSION['ID'].'</strong>';
       print 
    '<br>Your databased password is <strong>'.$_SESSION['pass'].'</strong></p>';
       print 
    '<p><a href="'.$_SERVER['PHP_SELF'].'?logout=Log-Me-Out">Click here to logout</a>.</p>';
     }
    ?>
    <form name="login" id="login" action="login.php" method="post" />
     <strong>Username: </strong>
       <input type="text" name="user" id="user" value="<?=$_SESSION['user']?>" /><br />
     <strong>Password: </strong>
       <input type="password" name="pass" id="pass" value="<?=$_SESSION['pass']?>" /><br />
     <input type="submit" name="submit" id="submit" value="Submit" />
    </form>
    • Basicly, This just gets the data from the session, and displays it on the page. The form will display the session varriables too.
    This is the more simple/secure hybrid..

    I'm not using an md5 encrypt directly, but the crypt() function works too.
    Last edited by s-p-n; 01-09-08 at 03:39 AM. Reason: Freshening up the Code


  2. #2
    Proficient Member AngryCat is offline
    MemberRank
    Jun 2007 Join Date
    *care*Location
    196Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Nice tut for beginners :D

    Quote Originally Posted by s-p-n View Post
    1. first field name: ID type: BIGINT extra: auto-increment Set to: Primary Key.
    Why not TINYINT?

  3. #3
    Gold Jamie is offline
    MemberRank
    Apr 2007 Join Date
    ScotlandLocation
    1,591Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Nice tutorials for begginers, keep em' coming.

  4. #4
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,098Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Quote Originally Posted by AngryCat View Post
    Nice tut for beginners :D



    Why not TINYINT?
    that would work too, but BIGINT was built for big numbers, and TINYINT was built for tiny numbers. For users, TINYINT would be sufficient, but say for instance this was for comments, the integer would get very large overtime.

    I don't really no the difference too well, but bigger is usually better :drinks_no

  5. #5
    Account Upgraded | Title Enabled! YoungJeezy is offline
    MemberRank
    Mar 2008 Join Date
    Your www directoryLocation
    211Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Very nice, thanks for this tut

  6. #6
    Gamma Daevius is offline
    MemberRank
    Jun 2007 Join Date
    NetherlandsLocation
    3,252Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Aye, nice. I normally do just an int, tinyint is way too small for a user base.

    Also, why do you ever do this:
    PHP Code:
    $db mysql_connect("$sql_host""$sql_user""$sql_pass") or die("Could not connect."); 
    You shouldn't really use variables inside strings like this, but this seems entirely unnecessary ^^.

  7. #7
    Account Upgraded | Title Enabled! Daney is offline
    MemberRank
    Jun 2007 Join Date
    1,110Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    PHP Code:
    $db mysql_connect("$sql_host""$sql_user""$sql_pass") or die("Could not connect."); 
    Should be:
    PHP Code:
    $db mysql_connect($sql_host$sql_user$sql_pass) or die("Could not connect."); 


    or change the ("Could not connect"); to (mysql_error());

    Anyway, the code looks okay :) Well done.

  8. #8
    Gamma Daevius is offline
    MemberRank
    Jun 2007 Join Date
    NetherlandsLocation
    3,252Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Quote Originally Posted by Daney View Post
    or change the ("Could not connect"); to (mysql_error());
    Nope, mysql_error() can display some valueble information for potentian hackers. Best to use mysql_errno(), or what he uses...though it can be helpful if you write the error away to a secured file (only viewable by you).

    That's why people write classes to handle DB input/output, to automate the error handling everytime you send a query, so it has not to be hardcoded for every query ;).

  9. #9
    Hm. foxx is offline
    MemberRank
    Sep 2006 Join Date
    Czech RepublicLocation
    5,257Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    sha1 for a password tbh

  10. #10
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,098Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Just curious, what's the differences (pluses, minuses) of md5, and crypt()? Is it always best to have a salt with a crypt()? And what's the purpose of ENCRYPT or sha1 in the SQL database? Text should be just as good if you encrypt it before putting it in the database, right? Or is using the built in ENCRYPT (or sha1) in SQL a shortcut?

    I know that the crypt function can either have 9 or 16 char encryptions, but md5 always has ..12(?) right? or 11 char or something around there.

    I think I might be mixed up with the char count.. but it's something like that.

    Is md5 dominate over crypt()? or does crypt() use the md5 anyway..?

  11. #11
    Omega Male Abry is offline
    MemberRank
    May 2008 Join Date
    4,500Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    nice tut
    i will try it
    and experiment on it
    and learn^^
    btw i am amazed on the coders how they do this^^
    i must have some time studying php and sql scripting and coding

  12. #12
    Gamma Daevius is offline
    MemberRank
    Jun 2007 Join Date
    NetherlandsLocation
    3,252Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    I don't really know what crypt does, PHP also has encryptions that change each time you encrypt the same thing...never saw how one could ever use it lawl.

    sha1 is known to be better then md5, mixing them both is even better.

  13. #13
    Proficient Member Virtue~ is offline
    MemberRank
    Jul 2008 Join Date
    181Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    This might help sumone:

    CREATE TABLE `users` (
    `ID` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `user` VARCHAR( 45 ) NOT NULL ,
    `pass` TEXT NOT NULL ,
    UNIQUE (
    `user`
    )
    ) ENGINE = MYISAM ;


    That is so you can execute the query without having to edit everything yourself

    EDIT: Tested and i love! http://darkcoders.co.nr/php/register.php <<<< Preveiw

  14. #14
    Account Upgraded | Title Enabled! YoungJeezy is offline
    MemberRank
    Mar 2008 Join Date
    Your www directoryLocation
    211Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Just a tip to everyone, before the ending backets in all of those php codes, put exit; and it won't show the login/register script after they have logged in, or finished registering, etc..

  15. #15
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,098Posts

    Re: [PHP+SQL] User Database in under 5 min. [Tut]

    Create a page with this: (install.php)
    PHP Code:
    <?php
    include("connect.php");
    $createUsrTbl ' CREATE TABLE `users` (
    `ID` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `user` VARCHAR( 45 ) NOT NULL ,
    `pass` TEXT NOT NULL ,
    UNIQUE (
    `user`
    )
    )'
    ;
    mysql_query($createUsrTbl) or die("<b>Error!</b> While attempting to create user database.<br>(You can not do this more than once.)");
    print 
    "User Database Created!!<br>Say <i>goodbye</i> (and thanks) to PhpMyAdmin!";  
    echo(
    '<p><a href="register.php">Redirecting to Register..</a></p>');
    echo(
    '<meta http-equiv="refresh" content="1;URL=register.php" />');
    ?>
    It won't work if you already have a database called users, so I put an error message saying (you can't do this twice) if it dies. (since that's the most likely thing causing the error.)

    If it can't connect, a connection generated die-message will appear (Ex: "Can not connect").

    I tested this, and it works.


    • Save it (or upload it) to server
    • Open the page once.
    • If it worked, delete the page from server. (It won't work more than one time, but you don't want an install page on the server)


    Thanks & credits to Virtue~ !
    :drinks_no
    Last edited by s-p-n; 10-08-08 at 05:28 PM. Reason: tested.



Page 1 of 2 12 LastLast

Advertisement