Description
A simple, MySQL-based login script, for people who Just Want To Get On With It.
Updates
*
05/03/07
Removed dependence on register_globals. Thanks to Sean Tuohy for pointing this one out.
*
13/07/06
Updated script to fix typo pointed out to me by the webmaster of QueerFM.
Instructions
Create your database table:
Code:
create table users (id int auto_increment, nick text, password text, email text, primary key(id));
Alter the database login details at the top; modify the bits in plain HTML to match your site design; save to a file; include at the top of any PHP-enabled page you wish to protect. Having anything (DOCTYPE, HTML, HEAD, whitespace...) before the opening <?php tag of the block containing the include statement will cause the script to fail.
Code
Code:
<?php
/* Simple Login script, by Twey */
/* (http://www.twey.co.uk/) */
/* Released under the terms of the */
/* GNU General Public License, version 2 or */
/* later. See http://www.gnu.org/copyleft/gpl.html */
/* for details. */
session_start();
$userstable = 'users';
mysql_pconnect('localhost', 'user', 'pass');
mysql_select_db('database');
function is_email($email) {
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c\\x00-\\x7f';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$addr_spec = "$local_part\\x40$domain";
return preg_match("!^$addr_spec$!", $email);
}
function head($title) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title><?php echo($title); ?></title>
<style type="text/css">
label {
display: block;
}
label.registerError {
border: 1px solid red;
}
span.registerError {
font-weight: bold;
color: red;
}
</style>
</head>
<body>
<?php
}
function foot() {
?>
</body>
</html>
<?php
}
function logout() {
session_destroy();
setcookie('nick', '', time() - 50);
setcookie('pass', '', time() - 50);
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
function loginForm() {
head("Log In");
?>
<form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post">
<p>
<label>
Username: <input type="text" name="nick">
</label>
<label>
Password: <input type="password" name="pass">
</label>
<label>
Remember me? <input type="checkbox" name="rem" value="true">
</label>
<label>
<input type="submit" value="Log in">
</label>
<a href="<?php echo($_SERVER['PHP_SELF']); ?>?register">Register</a>
</p>
</form>
<?php
foot();
}
function login() {
global $userstable, $key;
$data = isset($_POST['nick']) ? $_POST : $_COOKIE;
$nick = mysql_real_escape_string($data['nick']);
$pass = isset($_POST['nick']) ? md5($data['pass']) : $data['pass'];
$rs = mysql_query("select * from $userstable where nick='$nick' and password='$pass' limit 1;");
if(mysql_num_rows($rs) === 0)
die(noSuchUser());
else {
$row = mysql_fetch_array($rs);
$_SESSION['userid'] = $row['id'];
$nextweek = time() + (7 * 24 * 60 * 60);
$_SESSION['nick'] = $row['nick'];
$_SESSION['pass'] = $row['password'];
$_SESSION['email'] = $row['email'];
if(isset($_POST['rem'])) {
setcookie('nick', $_SESSION['nick'], $nextweek);
setcookie('pass', $_SESSION['pass'], $nextweek);
}
}
}
function noSuchUser() {
head('Error: User Doesn\'t Exist');
?>
<h1>Error: User Doesn't Exist</h1>
<p>
The username/password combination you have entered is not in our database. Please check that you have entered your username and password correctly. If you have not yet registered, you may do so <a href="<?php echo($_SERVER['PHP_SELF']); ?>?register">here</a>.
</p>
<?php
foot();
}
function registerForm($vals = array('', '', ''), $errors = array()) {
head("Register");
?>
<form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post">
<p>
<label<?php if(isset($errors[0])) echo(' class="registerError"'); ?>>
Username: <input type="text" name="nick" value="<?php echo(htmlentities($vals[0])); ?>">
<span class="registerError">
<?php if(isset($errors[0])) echo($errors[0]); ?>
</span>
</label>
<label<?php if(isset($errors[1])) echo(' class="registerError"'); ?>>
Password: <input type="password" name="pass" value="<?php echo(htmlentities($vals[1])); ?>">
<span class="registerError">
<?php if(isset($errors[1])) echo($errors[1]); ?>
</span>
</label>
<label<?php if(isset($errors[2])) echo(' class="registerError"'); ?>>
Email: <input type="text" name="email" value="<?php echo(htmlentities($vals[2])); ?>">
<span class="registerError">
<?php if(isset($errors[2])) echo($errors[2]); ?>
</span>
</label>
<label>
<input type="hidden" name="register" value="true">
<input type="submit" value="Register">
</label>
</p>
</form>
<?php
foot();
}
function register() {
global $userstable;
$nick = mysql_real_escape_string($_POST['nick']);
$pass = $_POST['pass'];
$email = mysql_real_escape_string($_POST['email']);
if(mysql_num_rows(mysql_query("select * from $userstable where nick='$nick';")))
die(userExists($_POST['nick']));
$errArr = array(
empty($_POST['nick']) ? 'Username must not be empty' : null,
empty($_POST['pass']) ? 'Password must not be empty' : null,
empty($_POST['email']) ? 'Email must not be empty' : null
);
$valArr = array(
$_POST['nick'],
'', // We don't restore the user's password value, since this is the default in most browsers, and the user will expect it.
$_POST['email']
);
if(strlen($_POST['nick']) > 20)
$errArr[0] = 'Username cannot be longer than 20 characters';
if(strlen($_POST['pass']) < 7)
$errArr[1] = 'Password must be longer than 7 characters';
if(empty($errArr[2]) && !is_email($_POST['email']))
$errArr[2] = 'This is not a valid email address';
for($i = 0; $i < count($errArr); $i++)
if(!empty($errArr[$i]))
die(registerForm($valArr, $errArr));
$pass = md5($pass);
// Actual registration
mysql_query("insert into $userstable (nick, password, email) values ('$nick', '$pass', '$email');") or die(mysql_error());
login();
}
function userExists($nick) {
head('Error: User Already Exists');
?>
<h1>Error: User Already Exists</h1>
<p>
The username "<?php echo(htmlentities($nick)); ?>" already exists in our database. Please check that you have entered your username and password correctly.
</p>
<?php
foot();
}
function validateUser() {
global $userstable;
$id = $_SESSION['userid'];
$nick = mysql_real_escape_string($_SESSION['nick']);
$pass = mysql_real_escape_string($_SESSION['pass']);
$email = mysql_real_escape_string($_SESSION['email']);
$rs = mysql_query("select * from $userstable where id=$id and nick='$nick' and password='$pass' and email='$email' limit 1;") or die(mysql_error());
if(!mysql_num_rows($rs))
die(loginForm());
}
if(isset($_GET['logout'])) logout();
else if(isset($_GET['register']))
die(registerForm());
else if(isset($_POST['register']))
register();
else if(!isset($_SESSION['nick']) && !isset($_POST['nick']) && !isset($_COOKIE['pass']))
die(loginForm());
else if(!isset($_SESSION['nick']) && (isset($_POST['nick']) || isset($_COOKIE['pass'])))
login();
else
validateUser();
?>
Bookmarks