FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


PHP & MySQL auth system





BlueVD
A lot of people seem to search for php auth systems not knowing how easy it is to make a simple one. A few other friends of mine asked me how to make a system in such a way so that if someone has changed their password to make it require re-authentication.
The answer is the Session vars and sessions. Again, most people know that SID's (session ID's) are not fully safe (since most people store them in cookies and such) and they might be sent in plain text. The following engine has a small trick to deal with that. Although, if you need a more iron-proof system I recommend building a more specialized system.
Here's the full engine with detailed explanations:

<?php
session_start
(); //start the session;
require_once("db.php"); //file with database definitions; explained later
$db=mysql_connect($mysqlh,$mysqlu,$mysqlp); //connection to the database server
if (!$db){ //if connection failed, them... there's a problem
die("ERROR in connecting to database engine: ".mysql_error());
}else{
$sdb=mysql_select_db($mysqld); //select the database
if (!$sdb){ //if there's a problem, alert the user
die("ERROR in selecting database: ".mysql_error());
}
}

if(isset(
$_SESSION['auth'])){//if the session has the 'auth' param set...
if (isset($_SESSION['user']) && isset($_SESSION['pass'])){ //check if the user is really authed
//the session global array will keep the username and password of the user in it
//this way you can check for SID's leaks and if a member changed a password
$query="select password from ".$utable." where username=\"".$_SESSION['user']."\"";
$pwdres=mysql_query($query); //get the password in the db for the username
$pwd=mysql_fetch_assoc($pwdres);
if(
$pwd['password']===$_SESSION['pass']){
$_SESSION['auth']='ok'; //the password in the db equals the password that was provided
}else{
session_destroy(); //the provided password in the session array doesn't match with the one in the database; either the user change the password or there's someone trying to forger a login/session
header('Location: http://'.$_SERVER['SERVER_ADDR'].$_SERVER['PHP_SELF']);
exit();
}
}
}else if (isset(
$_POST['username']) && isset($_POST['password'])){ //if there's no seesion but the username and password are passed from the form, try to auth
$query="select password from ".$utable." where username=\"".$_POST['username']."\"";
$pwdres=mysql_query($query);
$pwd=mysql_fetch_assoc($pwdres);
if(isset(
$pwd['password'])){
if(
$pwd['password']===$_POST['password']){
$_SESSION['user']=$_POST['username'];
$_SESSION['pass']=$_POST['password'];
$_SESSION['auth']='ok';
header('Location: http://'.$_SERVER['SERVER_ADDR'].$_SERVER['PHP_SELF']);
//
//die("good password & username");
//Do whatever you are required to do after auth
//
exit();
}else{
echo
"bad password";
}
}else{
echo
"Bad username!!!";
}
}
?>

<html>
<body>
<form action="?" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
<?php
//session_destroy();
?>

You'll notice that the above script has... 3 auth "states":

  • not authenticated (when none of the if's get triggered)
  • beginning of authentication (after submitting the form, the $_POST['...'] check
  • the authenticated state when the session is all ok (but can still be invalidated if the user changes his password).


The structure of db.php is simple:
<?php
$mysqlh="dbhost";
$mysqlu="dhuser";
$mysqlp="password";
$mysqld="database_name";
$utable="users_table";
?>

Now, in case you did not understand the engine from its code...
The script makes a few simple checks... First, it tries to see if there is a valid authentication. If there is, it checks the password (witch is stored in the Global SESSION array) with the password stored for the username in the database. The password in the array is stored upon a successful login. If the passwords don't match, it means that either the username changed the password or that someone is trying to forge a valid session. In this case you have the piece of code that destroys the session.
If the passwords match, then it means that everything is ok and the user has a valid auth.
On the second step, (in case there is no valid auth), the scrip checks to see if there are variables send by a login form. If they are, the script checks the user and password. If they match, it registers them in the SESSION array.
Now, based on your prefferences, you can use this system with redirects (header("location: http://....')), pages fetched from a database, etc...
My way is to include this file in each php script (with include_once) and this way the auth is checked on each page that is displayed. You can cut it down to your needs.
I hope it helps you.

PS: there are a lot of changes and other checks that can be made to this system. Including adding more security... This is just a small example =)
Manofgames
Cleansing the $_POST variables with mysql_real_escape_string wouldn't hurt Wink
Also, I'm not sure too many users would be happy to register on a site that didn't encrypt their passwords, and mysql_num_rows() might be better suited to finding if the user exists IMHO.
And wouldn't you use
Code:

<?php
echo "<form action='".$_SERVER['PHP_SELF']."' method='POST'>";
?>

instead of <form action="?" method="POST"> ?
I've just never seen it done that way before.
BlueVD
yeah, but like I said... it's a fast post... Also you could add the stripslashes() if the php.ini has the magic_quotes_gpc enabled... Use mysql password() to encrypt them.. and the form at the end was for testing purposes so that anybody can do a fast test for it (i did wrote it in vi and test it in lynx so I coded something fast). and also considering the usernames must be unique... mysql_fetch_assoc ain't that slow Wink
As to the form action as beein "?" it's ok according to w3c. only a null action isn't recommended.
roboguyspacedude
Yeah, you could elaborate and make a whole lot longer and fancier. For basics i guess it works, but my custom made auth system would owns this.
Related topics
E-Cards with PHP & MySQL
HTTP AUTH with PHP and mySQL
Crash course in PHP and MYSQL
Working with Excel, PHP & MySQL. Any Ideas
creating guestbooks (form) with php & mysql
A very good PHP MySQL Tutorial
Developing a Login System with PHP and MySQL
Flash, PHP and MySQL
PHP and MYSQL on the computer
Help regarding Php & MySQL
windows mobile programming and php, combination possible?
which host do u like put php&mysql?
php and mysql form
PHP-Fusion | An Open Source CMS | PHP & MySQL Based
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.