Hey guys,
I just spent all day trying to figure this out. I don't know if you've seen the tutorial by Martin Tsachev, but since my web host doesn't support the installation of PEAR packages, I decided to try to port this over to "regular" PHP code. I would really like to make use of the secure login methods that Tsachev sets forth, but my code just isn't working and I don't even know where to start fixing it. If anyone is bored this would be a fantastic help and me (and many others who don't have access to the PEAR DB module). I realize this is a lot of code but seriously I'm being brutally honest when I say this would make my year if someone would be able to help out a burned out coder in need.
Here's the original tutorial:
http://www.devshed.com/c/a/PHP/Creating-a-Secure-PHP-Login-Script/
And my code...
helper_functions.php
<?php
function sanitize($data)
{
$data = ereg_replace("[\'\")(;|`,<>]", "", $data);
$data = mysql_real_escape_string(trim($data));
return $data;
}
?>
db_connect.php
<?php
$mysql_host = '';
$mysql_user = '';
$mysql_password = '';
$mysql_database = '';
mysql_select_db($mysql_database, mysql_connect($mysql_host, $mysql_user, $mysql_password));
?>
auth_functions.php
<?php
require_once("db_connect.php");
require_once("helper_functions.php");
// auth_session_defaults(null)
// - Restores default session parameters when a user is not logged in
function auth_session_defaults()
{
$_SESSION["logged"] = false;
$_SESSION["uid"] = 0;
$_SESSION["username"] = "";
$_SESSION["cookie"] = 0;
$_SESSION["remember"] = false;
}
// auth_validate_login(string, string, boolean)
// - Accepts a username and password, verifies them, and
// if valid, logs in the user
function auth_validate_login($username, $password, $remember)
{
$username = sanitize($username); // sanitize the username
$password = sanitize(md5($password)); // sanitize the password
$result = mysql_query("SELECT * FROM `members` WHERE " .
"`username` = '$username' AND " .
"`password` = '$password'");
if (mysql_num_rows($result) == 1) // if the credentials are valid
{
$user = mysql_fetch_array($result); // get the row as an array and assign it to $user
auth_start_session($user, $remember); // log in the user
return true; // exit the function with TRUE
}
else
{
auth_logout(); // log out the user if the credentials are not valid
return false; // exit the function with FALSE
}
}
// auth_start_session(array, boolean, boolean)
// - Sets the session variables and sends the cookie for persistent login if requested
// - The last parameter determines whether this is an initial login or a subsequent
// session check
function auth_start_session($user, $remember, $inital_login = true)
{
$_SESSION["uid"] = $user["id"]; // set UID session variable to the user id in the database
$_SESSION["username"] = $user["id"]; // set username session variable to the username in the database
$_SESSION["cookie"] = $user["cookie"]; // set the cookie session variable to the cookie in the database
$_SESSION["logged"] = true; // set logged in to true
if ($remember)
{
auth_update_cookie($user["cookie"],true); // if the user requests to be remembered, then update the cookie and save it
}
if ($initial_login) // if this is an initial login
{
$session_id = sanitize(session_id()); // obtain the session id
$ip = sanitize($_SERVER["REMOTE_ADDR"]);
$result = mysql_query("UPDATE `members` SET " .
"`session` = '$session_id', " .
"`ip` = '$ip', WHERE " .
"`id` = '" . $_SESSION["uid"]."'"); // stores session information
}
}
// auth_update_cookie(? , boolean)
// - allow skipping the login procedure on each visit to the site
function auth_update_cookie($cookie, $save)
{
$_SESSION['cookie'] = $cookie; // assigns the passed $cookie varaible to the cookie session variable
if ($save)
{
$cookie = serialize(array($_SESSION["username"], $cookie));
setcookie("mtwebLogin", $cookie, time()+31104000, "/directory/", ".testdomain.com");
}
}
// auth_validate_cookie
// -
function auth_validate_cookie($cookie)
{
list($username, $cookie) = @unserialize(stripslashes($cookie));
if (!$username || !$cookie)
{
return false;
}
$username = sanitize($username);
$cookie = sanitize($cookie);
$result = mysql_query("SELECT * FROM `members` WHERE " .
"(`username` = '$username') AND (`cookie` = '$cookie')");
if (mysql_num_rows($result) == 1)
{
$user = mysql_fetch_array($result);
auth_set_session($user, true, false); // false? not sure if it should be there
}
}
// auth_validate_session
function auth_validate_session()
{
$username = sanitize($_SESSION["username"]);
$cookie = sanitize($_SESSION["cookie"]);
$session_id = sanitize(session_id());
$ip = sanitize($_SERVER["REMOTE_ADDR"]);
$result = mysql_query("SELECT * FROM `members` WHERE " .
"(`username` = '$username') AND (`cookie` = '$cookie') AND " .
"(`session` = '$session_id') AND (`ip` = '$ip')");
if (mysql_num_rows($result) == 1)
{
$user = mysql_fetch_array($result);
auth_start_session($user, true, false); // false? not sure if it should be there
}
else
{
auth_logout();
}
}
function auth_logout()
{
session_unset();
session_destroy();
}
?>
sample_page.php
<?php
require_once("auth_functions.php");
auth_validate_login("test", "password", true); // should log in the test user stored in DB
if ($_SESSION["logged"])
{
echo "session result: ".auth_validate_session();
}
elseif (isset($_COOKIE["mtwebLogin"]))
{
echo "cookie result: ".auth_validate_cookie();
}
else
{
echo "not logged in.";
}
?>
And finally, the database schema:
CREATE TABLE member (
id int NOT NULL auto_increment,
username varchar(20) NOT NULL default '',
password char(32) binary NOT NULL default '',
cookie char(32) binary NOT NULL default '',
session char(32) binary NOT NULL default '',
ip varchar(15) binary NOT NULL default '',
PRIMARY KEY (id),
UNIQUE KEY username (username)
);