A Simple PHP/MySQL Authentication Script for Logins

Page last updated on 2011 / 04 / 09

Creating a login area with PHP and MySQL is very easy! The script provided here can be easily customized should you wish to have an area of your site behind a login. The script uses PHP and MySQL and can be adapted to suit your needs.

Apply the following SQL to an existing database:

  1. CREATE TABLE IF NOT EXISTS `userlist` (
  2. `id` smallint(5) unsigned NOT NULL,
  3. `username` varchar(32) NOT NULL,
  4. `password` binary(16) NOT NULL,
  5. `session` binary(16) NOT NULL,
  6. PRIMARY KEY (`id`),
  7. UNIQUE KEY `username` (`username`),
  8. UNIQUE KEY `session` (`session`)
  9. ) ENGINE=MyISAM;
  10.  
  11. INSERT INTO userlist (id,username,password,session) VALUES ('','innvo',UNHEX(MD5('innvo')),UNHEX(MD5('innvo')));
  12.  

See the script comments to get an idea of how the code works. I have created a single account where both the username and password are 'innvo'.

  1. <?php
  2.  
  3. // Enter your MySQL username, password and database name here
  4. mysql_connect('localhost','root','root') or die(mysql_error());
  5. mysql_select_db('stuff') or die(mysql_error());
  6.  
  7. function user_login()
  8. {
  9. // This form displays until the user successfully logs in
  10. $form = '<div style="border:1px dotted #CDE;padding:15px;" align="center">
  11. <form method="post">
  12. <h4>Login Area</h4>
  13. <p>Username: <input type="text" name="username" size="15" /></p>
  14. <p>Password: <input type="password" name="password" size="19" /></p>
  15. <p><input type="submit" value="Login" />
  16. </form>
  17. </div>';
  18. if(isset($_POST['username'],$_POST['password']))
  19. {
  20. // username and password submitted, check the database
  21. $query = mysql_query('SELECT id,UPPER(HEX(password)) AS password
  22. FROM userlist
  23. WHERE username = \''.mysql_real_escape_string($_POST['username']).'\'') or die(mysql_error());
  24.  
  25. if(($user = mysql_fetch_array($query,MYSQL_ASSOC)) && strtoupper(md5($_POST['password'])) == $user['password'])
  26. {
  27. // Create cookie
  28. $user_cookie = strtoupper(md5(uniqid(rand(),true)));
  29. setcookie('user',$user_cookie,false,'/',false);
  30. // Update database with unique cookie value for further authentication, then re-direct user (who is now logged in)
  31. mysql_query('UPDATE userlist SET session = UNHEX(\''.$user_cookie.'\') WHERE id = '.$user['id']) or die(mysql_error());
  32. header('Location: http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
  33. exit(0);
  34. }
  35. else
  36. die('<p>Invalid Username and password.</p>'.$form); // Invalid login
  37. }
  38. elseif(isset($_COOKIE['user']))
  39. {
  40. // user cookie exists, check to see if it matches a login session in the database
  41. $query = mysql_query('SELECT id
  42. FROM userlist
  43. WHERE session = UNHEX(\''.mysql_real_escape_string($_COOKIE['user']).'\')');
  44. if(!$user = mysql_fetch_array($query,MYSQL_ASSOC))
  45. die('<p>Previous login has expired.</p>'.$form); // Invalid (or expired) session
  46. return $user;
  47. }
  48. else
  49. die($form);
  50. }
  51.  
  52. $user = user_login();
  53. // User is logged in here, you can now reference the users account by using $user['id']
  54. print_r($user);
  55.  
  56. ?>
  57.  

Some notes regarding the script:


Previous Article
A Simple PHP/XML Sitemap Generator
Next Article
Storing Websites in Memory Using PHP




Tweet