home *** CD-ROM | disk | FTP | other *** search
- MySQL Cookie Auth
-
- Need to authenticate users for an application, expire sessions after certain amounts of time and verify them upon page loads?
-
-
-
- <?php
- /****************************************************************
-
- These functions expect a table definition
- that looks something like this:
-
- CREATE TABLE users (
- user_id int(32) unsigned NOT NULL DEFAULT '0' auto_increment,
- user_name varchar(16) NOT NULL,
- password varchar(16) NOT NULL,
- PRIMARY KEY (user_id),
- UNIQUE idx_user_id (user_id),
- KEY (user_name),
- UNIQUE idx_user_name (user_name)
- );
-
- ****************************************************************/
-
- function db_connect() {
- $user = "your_username";
- $pass = "your_password";
- $server = "your.database.server.your.net";
- $connection = mysql_pconnect($server, $user, $pass);
- return $connection;
- }
-
- function login($user_name, $password) {
- /* Connect to the database, and setup our SQL statement */
- $db = "your_database";
- $SQL = "SELECT * FROM users WHERE user_name ='$user_name'";
- $connection = db_connect();
- /* Run the query */
- $query = mysql_db_query($db, $SQL, $connection);
- /* Fetch the result */
- $row = mysql_fetch_array($query);
- /* Verify */
- if (($row[ "user_name"] == $user_name)
- AND ($row[ "password"] == $password)
- AND ($user_name != "")){
- /* User has been validated. Drop the cookie */
- $user_id = $row[ "user_id"];
- $md5pw = md5($password);
- /* time() + 3600 is one hour from now */
- SetCookie( "TheLoginCookie", "$user_id:$md5pw", time()+3600);
- $value = 1;
- } else {
- $value = 0;
- }
- return $value;
- }
-
-
- function verify_auth($cookie){
- /* Split the cookie up into user_id and md5(password) */
- $auth = explode( ":", $cookie);
- $db = "your_database";
- $connection = db_connect();
- $SQL = "SELECT * FROM users WHERE user_id = '$auth[0]'";
- $query = mysql_db_query($db, $SQL, $connection);
- $row = mysql_fetch_array($query);
- $md5pw = md5($row[ "password"]);
- if (($row[ "user_id"] == $auth[0])
- AND ($md5pw == $auth[1])
- AND ($auth[0] != "")) {
- $value = 1;
- } else {
- $value = 0;
- }
- return $value;
- }
-
-
- ?>
-
-