bottom
wait
Valid XHTML 1.0!
Get Firefox!
Programming tutorials - User authentication (PHP)
This tutorial will teach you how to make a login form with PHP and MySQL. You'll also learn how to work with php sessions.
The secure file by login is protected.php, in this way it couldn't access it directly without passing the login section.
The data base will contain a table with name users with 3 columns: user, password and session_id. In password field we'll insert the password in MD5.
We start with creation of index.php in which we find a form where you can insert user and password. On the first line (only the first) is initiating a session by appeal of session_start() function, after this we destroy it. You'll see below why the session must be destroy, immediately after it was created.
We'll include the functions.php file, about which we talk immediately, and below form we appeal login_message() function from functions.php for show if in login process was appear an error.
index.php
  1. <?php session_start();
  2. session_unset();
  3. session_destroy();
  4. include("functions.php");
  5. ?>
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  7. <html xmlns="http://www.w3.org/1999/xhtml">
  8. <head>>
  9. <title>Login</title>
  10. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  11. </head>
  12. <body>
  13. <form name="login" action="loginaction.php" method="post">
  14. User: <input type="text" name="user" /><br />
  15. Pass: <input type="password" name="pass" /><br />
  16. <input type="submit" name="login" value="Log In" />
  17. </form>
  18. <?php login_message(); ?>
  19. </body>
  20. </html>
Once you click the submit button from index.php, you'll send the informations to be validate. This thing we'll do it in loginaction.php file.
We'll get the date from form and we search its in data base. Before to make this thing we initiate the session on the first line and we include the file functions.php that contain amoung other things the connection to data base.
If date insered in form wasn't found in data base is appealing the function login_failed($err='nu') but if the date was found we apeal the function login_good($_POST['user']).
I want to make an observation, the password will be always encrypted, for a better security.
loginaction.php
  1. <?php session_start();
  2. include("functions.php");
  3. $sql = 'SELECT * FROM users WHERE user="'.$_POST['user'].'" AND password="'.md5($_POST['pass']).'"';
  4. $query = mysql_query($sql) or die(mysql_error());
  5. $row = mysql_fetch_object($query);
  6. $login_or_not = mysql_num_rows($query);
  7. if(md5($_POST['user']) != md5($row->user) || md5($_POST['pass']) != $row->password || $login_or_not != 1){
  8. login_failed($err='nu');
  9. }
  10. else login_good($_POST['user']);
  11. ?>
The file functions.php contain the informations about data base (the values of those variables must be changed with yours), as well as those 3 functions appealed in index.php and loginaction.php and a function that we'll use it in every file that we want to password.
In the moment when the submit button is clicked, the variables containing user and password are sending to loginaction.php, if is not found any result we appeal function login_failed($err='nu') that redirect the page to index.php?login=no. Look at global variable $_GET['login'], sended in the moment when user and password were invalids. When this variable exist the execution of code enter in if condition from login_message() and display an error message.
But if user and password are valids, we appeal the function login_good($user), where $user is the value of user's field from index.php. Here we define session_id() assigned to $_SESSION['key_user'] and valid user assigned to $_SESSION['user_good'], then we update the data base with the new session_id() for to be loged only one person in the same time. All we have to do is to redirect the page to protected.php.
I must mention here, because this tutorial is a start in learning how to work with php sessions, that a superglobal variable $_SESSION is sended to other page by appeal of session_start() function. The $_SESION['key_user'] and $_SESSION['user_good'] will be send to protected.php and far away by simply continuity of session_start on the first line.
functions.php
  1. <?php
  2. /* Information about data base */
  3. $user='root';
  4. $pass='';
  5. $server='localhost';
  6. $data_base='test';
  7. /* Connection to data base */
  8. $connect=mysql_connect($server, $user, $pass) or die (mysql_error());
  9. $select_db=mysql_select_db($data_base, $connect) or die (mysql_error());
  10. // MESSAGE FOR LOGIN ERRORS
  11. function login_message(){
  12. if($_GET['login']=='no'){
  13. $message='Wrong user or password!';
  14. echo $message;
  15. }
  16. else{
  17. echo '&nbsp;';
  18. }
  19. }
  20. // LOGIN ERROR
  21. function login_failed(){
  22. echo '<script type="text/javascript"><!--
  23. window.location.href="index.php?login=no";
  24. //--></script>';
  25. }
  26. // LOGIN IS OK
  27. function login_good($user){
  28. $_SESSION['key_user'] = session_id();
  29. $_SESSION['user_good'] = $user;
  30. $sql = 'UPDATE users SET session_id="'.$_SESSION['key_user'].'" WHERE user="'.$user.'";';
  31. mysql_query($sql) or die(mysql_error());
  32. echo '<script type="text/javascript"><!--
  33. window.location.href="protected.php";
  34. //--></script>';
  35. }
  36. // IF LOGIN IS OK THAN WILL VERIFY IF USER IS STILL LOGED
  37. function check_session(){
  38. $sql = 'SELECT count(*) AS ses FROM users WHERE session_id="'.$_SESSION['key_user'].'" AND user="'.$_SESSION['user_good'].'"';
  39. $query = mysql_query($sql) or die(mysql_error());
  40. $row = mysql_fetch_object($query);
  41. $session = $row->ses;
  42. if($session != 1) login_failed();
  43. else return true;
  44. }
  45. ?>
Once directed to protected.php, we initiate here, like in every page on the first line, the function session_start(), we include the file functions.php and we verify if login process was sucesfuly by apealing the check_session() functoin. Is recommended to put this function after incude of functions.php. The apeal of this function it suppose a select in data base of insered user an the session_id ($_SESSION['key_user']), that was created and updated in login_good() function. If this function don't return the result 1, we apeal login_failed() function that will redirect the page to index.php and will display an error result. But if the search in data base will return only one result, we continue to display the protected.php page where we put a link to log out, the click on this link redirect page to index.php where we destroy the session with function session_unset() and session_destroy(), in this way if we click the back button of browser or we write in address bar the name of protected file (protected.php) will redirect the page to index.php page and will display an error message because the session was destroy and the variables $_SESSION['user_good'] and $_SESSION['key_user'] don't exist no more.
To protect any other page just insert in every page you want to protect the function check_session(), session_start() on the first line and include the functions.php file.
protected.php
  1. <?php session_start();
  2. include("functions.php");
  3. check_session();
  4. ?>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  6. <html xmlns="http://www.w3.org/1999/xhtml">
  7. <head>
  8. <title>Wellcome</title>
  9. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  10. </head>
  11. <body>
  12. Wellcome <?php echo $_SESSION['user_good']; ?>.
  13. You can now <a href="index.php">LOG OUT</a>
  14. </body>
  15. </html>
CREATE TABLE `users` (
`user` text NOT NULL,
`password` text NOT NULL,
`session_id` text NOT NULL
) TYPE=MyISAM ;

INSERT INTO `users` VALUES ('admin', '21232f297a57a5a743894a0e4a801fc3', 'session');
Print this page
bottom