• Unfortunately, we have experienced significant hard drive damage that requires urgent maintenance and rebuilding. The forum will be a state of read only until we install our new drives and rebuild all the configurations needed. Please follow our Facebook page for updates, we will be back up shortly! (The forum could go offline at any given time due to the nature of the failed drives whilst awaiting the upgrades.) When you see an Incapsula error, you know we are in the process of migration.

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

Status
Not open for further replies.
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
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:
<?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'], 0, 2);
   $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:
<?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:
<?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:
<?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'], 0, 2);
    $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:
<?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:
Gold
Loyal Member
Joined
Apr 28, 2007
Messages
1,104
Reaction score
22
Nice tutorials for begginers, keep em' coming.
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
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
 
Custom Title Activated
Loyal Member
Joined
Jun 28, 2007
Messages
2,986
Reaction score
3
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:
$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 ^^.
 
Skilled Illusionist
Loyal Member
Joined
Jun 23, 2007
Messages
310
Reaction score
1
PHP:
$db = mysql_connect("$sql_host", "$sql_user", "$sql_pass") or die("Could not connect.");
Should be:
PHP:
$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.
 
Custom Title Activated
Loyal Member
Joined
Jun 28, 2007
Messages
2,986
Reaction score
3
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 ;).
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
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..?
 
Omega Male
Loyal Member
Joined
May 12, 2008
Messages
2,547
Reaction score
437
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
 
Custom Title Activated
Loyal Member
Joined
Jun 28, 2007
Messages
2,986
Reaction score
3
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.
 
Junior Spellweaver
Joined
Jul 6, 2008
Messages
173
Reaction score
2
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! <<<< Preveiw
 
Experienced Elementalist
Joined
Mar 18, 2008
Messages
205
Reaction score
0
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..
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Create a page with this: (install.php)
PHP:
<?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:
Junior Spellweaver
Joined
Jul 6, 2008
Messages
173
Reaction score
2
no need to credit me really, querys show up after you input all the things ;)
 
Experienced Elementalist
Joined
Apr 15, 2008
Messages
256
Reaction score
0
Thank you so much for making this guide!
It has helped me so much!
 
Status
Not open for further replies.
Back
Top