Be a Supporter!

Php: User Authentication (part 1)

  • 1,995 Views
  • 12 Replies
New Topic Respond to this Topic
Greeley
Greeley
  • Member since: Aug. 30, 2005
  • Offline.
Forum Stats
Member
Level 13
Blank Slate
Php: User Authentication (part 1) 2005-12-15 00:13:54 Reply

PHP: Main

User Authentication (Part 1)

Welcome to my user authentication tutorial. User authentication is when you set up a system for your websites users so they can signup and login with there own accounts. In this tutorial we'll show you how to create the signup form and then process the data.

What you must already know:
You must know how to set up a MySQL table using either phpMyAdmin or just by using PHP. It'll help if you know html/xhtml when following this tutorial. You can learn the following at www.w3schools.com. Also it's a must that you know the basics of PHP scripting.

What we will accomplish:
Throughout my User Authentication tutorials you will accomplish a user signup and login. The user will be required to activate there account by an activation email. After that we will work with sessions so the user can login.

The Database Table:
For starters we need a MySQL table to submit the information for each user. All you should need is the following columns:
Userid (integer auto_increment)
Username
Password(Must be 32 characters long because of the md5 function we add for security.)
Email
(It's optional but you may add any other fields once you get the hang of how this works).

The SignUp Form:
This is the easy part. We just need to create an html form that the user will submit the information into. Here it is how we'll do this:

<form action="processsignup.php" method="post">
Username:
<input type="text" name="username" size="15" maxlength="15">
<br />
Password:
<input type="password" name="password1" size="15" maxlength="15">
<br />
Confirm Password:
<input type="password" name="password2" size="15" maxlength="15">
<br />
Email Address
<input type="password" name="email" size="15" maxlength="15">
<br />
<input type="Submit" value="Sign Up">
</form>

That's how we'll set up the form. Save the file as signup.html or whatever you want.

Processing the Form:
Now for the fun php that processes the form. It makes sure that there are no errors and secures the information. If errors occur then we'll tell the users what went wrong. We'll be using the header function to redirect users to previously created error pages. So first, set up your page like this:
<?php
ob_start();
?>
<html>
<head>
<title>title</title>
</head>
<body>
<?php
(processing script will go here!)
?>
</body>
</html>
<?php
ob_end_flush();
?>

If you do not set up your page like this you may enouncter some errors with the header function. Okay, now for processing the page:

<?php

// Get values from the signup form
$username = $_POST['username'];
$pswrd1 = $_POST['password1'];
$pswrd2 = $_POST['password2'];
$email = $_POST['email'];

// Lets make sure that everything was filled in.
if ( (!$username) || (!$pswrd1) || (!$pswrd2) || (!$email) )
{
header("Location: error-requirednotfilled.php");
exit;
}

// If passwords aren't the same then exit the script and redirect to previously created page.
if ( $pswrd1 != $pswrd2 )
{
header("Location: error-passwordsnotequal.php");
exit;
}

// Now lets create a few functions to make sure that only certain characters are used
// Only allow a-z,0-9,_, and - in the username
function CheckUsername($username)
{
if (eregi('^[A-Z0-9_.-]{1,}', $username))
{
return true;
}
else
{
return false;
}
}

if (!CheckUsername($username))
{
header("Location: error-wrongcharactersinusername.php");
die();
}

// Only allow a-z,0-9,_, and - in the password
// You will only need to do this for password since they must be equal anyways.
function CheckPassword($pswrd1)
{
if (eregi('^[A-Z0-9_.-]{1,}', $pswrd1))
{
return true;
}
else
{
return false;
}
}

if (!CheckPassword($pswrd1))
{
header("Location: error-wrongcharactersinpassword.php");
die();
}

// This not only checks to make sure that the email is correct but that it exists and is
// In the proper format.
function checkEmail($email)
{
if(eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[
a-zA-Z0-9\-\.]+$]", $email))
{
return FALSE;
}

list($Username, $Domain) = split("@",$email);

if(getmxrr($Domain, $MXHost))
{
return TRUE;
}
else
{
if(fsockopen($Domain, 25, $errno, $errstr, 30))
{
return TRUE;
}
else
{
return FALSE;
}
}
}

if (!CheckEmail($email))
{
header("Location: error-inproperemail.php");
die();
}

// Final part of this script. Lets make sure that the username and password are
// No less than 6 characters in length. Instead of redirecting with header we will use echo.
$minlength = 6;
if ( strlen($username) < $minlength || strlen($pswrd1) < $minlength )
{
echo 'The following must be at least 6 characters long:<br />';
if ( strlen($username) )
{
echo 'username<br />';
}
if ( strlen($pswrd1) )
{
echo 'password';
}
}

?>

That's all I'm covering in part 1. I will do part 2 when I have the time and got nothing else to do.

What'll be in part 2?
In part 2 you will learn how to use the mysql_query function along with some other neat mysql() functions. We will be checking to make sure that the username does not already exist. We will also be sending an activation email for activating the account. Thankyou for reading my second tutorial.

IWantSomeCookies
IWantSomeCookies
  • Member since: Aug. 20, 2004
  • Offline.
Forum Stats
Member
Level 13
Blank Slate
Response to Php: User Authentication (part 1) 2005-12-15 18:00:02 Reply

Wow! This is real nice! Thanks for the tutorial. :-)


"Actually, the server timed out trying to remove all your posts..."
-TomFulp

Greeley
Greeley
  • Member since: Aug. 30, 2005
  • Offline.
Forum Stats
Member
Level 13
Blank Slate
Response to Php: User Authentication (part 1) 2005-12-15 20:03:34 Reply

At 12/15/05 06:00 PM, IWantSomeCookies wrote: Wow! This is real nice! Thanks for the tutorial. :-)

No problem. Hope everyone awaits part 2 and further parts beyond that. I just whip these up in like half an hour. So if there are any errors tell me.

Greeley
Greeley
  • Member since: Aug. 30, 2005
  • Offline.
Forum Stats
Member
Level 13
Blank Slate
Response to Php: User Authentication (part 1) 2005-12-24 00:27:00 Reply

Today I learnt that the match_preg() function is much better to use than ereg or eregi... So I redid the functions for checking to make sure the proper characters were used in the names. Here is how you should do it instead:

<?php
// create functions to check formats of fields
// check email function
function CheckEmail($email)
{
if(preg_match("/^[A-z0-9][\w.-]*@[A-z0-9][
\w\-\.]+\.[A-z0-9]{2,6}$/", $email))
{
return true;
} else {
return false;
}
}

// check username function
function CheckUsername($username)
{
if(preg_match("/^[A-z0-9_-]{1,}$/", $username))
{
return true;
}
else
{
return false;
}
}

// check password function
function CheckPassword($pswrd1)
{
if(preg_match("/^[A-z0-9_-]{1,}$/", $pswrd1))
{
return true;
}
else
{
return false;
}
}

?>

whatthedeuce
whatthedeuce
  • Member since: Jun. 4, 2005
  • Offline.
Forum Stats
Member
Level 02
Blank Slate
Response to Php: User Authentication (part 1) 2005-12-24 01:20:23 Reply

Unless I'm mistaken, the CheckUsername and CheckPassword functions are exactly the same. Why not just have one checkValid function that does the same thing?

Craige
Craige
  • Member since: Jul. 17, 2004
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to Php: User Authentication (part 1) 2005-12-24 01:53:30 Reply

At 12/24/05 01:20 AM, whatthedeuce wrote: Unless I'm mistaken, the CheckUsername and CheckPassword functions are exactly the same. Why not just have one checkValid function that does the same thing?

Because it is good programming to make your functions do ONE task. And now, if he wishes to add different checks for either the username or the password, he does not have to go back to all of his code that uses checkValid, and either edit it's paramaters in the script to account for new ones added to teh defination, or just replace them with the function names he has now. His way allows him to just edit the function definations and have them preform different tasks on eiher the password or the username easily.

However though, there is not really a reason to only allow certain characters through for the password. You are going to be encoding it anyway, so why limit what they can use for it? The password will not be put back to it's origonal text on you page, so there is no fear of injections. Just let them use what they wish.

Greeley
Greeley
  • Member since: Aug. 30, 2005
  • Offline.
Forum Stats
Member
Level 13
Blank Slate
Response to Php: User Authentication (part 1) 2005-12-24 04:29:42 Reply

Yeah you could probably just let them use what they wish... I myself prefer to actually limit what they can use. Don't ask why... I just like it!

Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to Php: User Authentication (part 1) 2005-12-24 10:23:23 Reply

Your check username function has a few glitches. You're only telling the ereg() function to check for "One or more characters in this character set at the beginning of the string" which does you really no good. You should put a $ seeded at the end of the regular expression to denote it should ONLY match that set from beginning to end.

Also, I wouldn't use ereg()....ever. Try something like this:

function CheckUsername($string) {
$check = preg_match('#^[A-Za-z_0-9]{3,}$#i', $string); // Whatever your char class was
if (!$check) {
return false;
} else {
return true;
}
}

I made the username be at least 3 characters long, because in my opinion, one or two character usernames are just annoying as hell. If you want to make it one or more characters that's fine too. You can use the + operator for regular expressions which does the same thing as {1,}.

Taylor
Taylor
  • Member since: Aug. 19, 2003
  • Offline.
Forum Stats
Member
Level 09
Blank Slate
Response to Php: User Authentication (part 1) 2005-12-24 15:11:18 Reply

At 12/24/05 10:23 AM, Pilot-Doofy wrote: I made the username be at least 3 characters long, because in my opinion, one or two character usernames are just annoying as hell.

I'm changing my mustywindows username to a letter.

Greeley
Greeley
  • Member since: Aug. 30, 2005
  • Offline.
Forum Stats
Member
Level 13
Blank Slate
Response to Php: User Authentication (part 1) 2005-12-24 16:22:07 Reply

Yeah it's good to make sure it's more than so many characters but you don't have to do this using the preg_match() function. You can just use str_len() to do it and make sure it's not less than 3...

NinoGrounds
NinoGrounds
  • Member since: Nov. 28, 2005
  • Offline.
Forum Stats
Member
Level 19
Programmer
Response to Php: User Authentication (part 1) 2006-03-02 11:37:20 Reply

Well, good, but the real trick would be part 2 (sessions)

FireBred
FireBred
  • Member since: Feb. 26, 2006
  • Offline.
Forum Stats
Member
Level 05
Blank Slate
Response to Php: User Authentication (part 1) 2006-03-02 14:59:06 Reply

Just out of curiosity, why would you wanna limit passwords to '1-9, a-z and _ -'?
Assuming someone managed to get to view you database and md5 hash using only the 37 characters you're allowing wouldn't take much to crack.

Any reason why you limit them at all?

henke37
henke37
  • Member since: Sep. 10, 2004
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to Php: User Authentication (part 1) 2006-03-02 15:48:44 Reply

He has chosen removing dangerous characters instead of neutralising them.
Passwords gets hashed, a hash is just a number.
A user name should both be filtered to be safe in database querys and in another layer filtered to not cause html trouble when output.


Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.