home *** CD-ROM | disk | FTP | other *** search
/ H4CK3R 4 / hacker04 / 04_HACK04.ISO / src / PHP / mysqlcookieauth.php3.txt < prev    next >
Encoding:
Text File  |  2002-05-06  |  2.3 KB  |  81 lines

  1. MySQL Cookie Auth 
  2.  
  3. Need to authenticate users for an application, expire sessions after certain amounts of time and verify them upon page loads? 
  4.  
  5.  
  6.  
  7. <?php 
  8. /**************************************************************** 
  9.  
  10. These functions expect a table definition 
  11. that looks something like this: 
  12.  
  13. CREATE TABLE users ( 
  14.   user_id int(32) unsigned NOT NULL DEFAULT '0' auto_increment, 
  15.   user_name varchar(16) NOT NULL, 
  16.   password varchar(16) NOT NULL, 
  17.   PRIMARY KEY (user_id), 
  18.   UNIQUE idx_user_id (user_id), 
  19.   KEY (user_name), 
  20.   UNIQUE idx_user_name (user_name) 
  21. ); 
  22.  
  23. ****************************************************************/ 
  24.  
  25. function db_connect() { 
  26.   $user =  "your_username"; 
  27.   $pass =  "your_password"; 
  28.   $server =  "your.database.server.your.net"; 
  29.   $connection = mysql_pconnect($server, $user, $pass); 
  30.   return $connection; 
  31.  
  32. function login($user_name, $password) { 
  33.    /* Connect to the database, and setup our SQL statement */ 
  34.   $db =  "your_database"; 
  35.   $SQL =  "SELECT * FROM users WHERE user_name ='$user_name'"; 
  36.   $connection = db_connect(); 
  37.    /* Run the query */ 
  38.   $query = mysql_db_query($db, $SQL, $connection); 
  39.    /* Fetch the result */ 
  40.   $row = mysql_fetch_array($query); 
  41.    /* Verify */ 
  42.   if (($row[ "user_name"] == $user_name)  
  43.       AND ($row[ "password"] == $password)  
  44.       AND ($user_name !=  "")){ 
  45.      /* User has been validated.  Drop the cookie */ 
  46.     $user_id = $row[ "user_id"]; 
  47.     $md5pw = md5($password); 
  48.      /* time() + 3600 is one hour from now */ 
  49.     SetCookie( "TheLoginCookie",  "$user_id:$md5pw", time()+3600); 
  50.     $value = 1; 
  51.   } else { 
  52.     $value = 0; 
  53.   } 
  54.   return $value; 
  55.  
  56.  
  57. function verify_auth($cookie){ 
  58.    /* Split the cookie up into user_id and md5(password) */ 
  59.   $auth = explode( ":", $cookie); 
  60.   $db =  "your_database"; 
  61.   $connection = db_connect(); 
  62.   $SQL =  "SELECT * FROM users WHERE user_id = '$auth[0]'"; 
  63.   $query = mysql_db_query($db, $SQL, $connection); 
  64.   $row = mysql_fetch_array($query); 
  65.   $md5pw = md5($row[ "password"]); 
  66.   if (($row[ "user_id"] == $auth[0])  
  67.       AND ($md5pw == $auth[1])  
  68.       AND ($auth[0] !=  "")) { 
  69.     $value = 1; 
  70.   } else { 
  71.     $value = 0; 
  72.   } 
  73.   return $value; 
  74.  
  75.  
  76. ?> 
  77.  
  78.