config.php
<?php
error_reporting(E_ALL);
include_once("functions.php");
session_register("nickname");
session_register("password");
session_register("loggedIn");
$messages=array();
$dbhost="localhost";
$dbuser="root";
$dbpass="";
$dbname="login";
connectToDB();
?>
function.php
<?php
function connectToDB() {
global $link, $dbhost, $dbuser, $dbpass, $dbname;
($link = mysql_pconnect("$dbhost", "$dbuser", "$dbpass")) || die("Couldn't connect to MySQL");
// select db:
mysql_select_db("$dbname", $link) || die("Couldn't open db: $dbname. Error if any was: ".mysql_error() );
} // end func dbConnect();
function newUser($nickname, $password) {
global $link;
$query="INSERT INTO users (nickname, password) VALUES('$nickname', '$password')";
$result=mysql_query($query, $link) or die("Died inserting login info into db. Error returned if any: ".mysql_error());
return true;
} // end func newUser($nickname, $pass)
function displayErrors($messages) {
print("<b>There were problems with the previous action. Following is a list of the error messages generated:</b>\n<ul>\n");
foreach($messages as $msg){
print("<li>$msg</li>\n");
}
print("</ul>\n");
} // end func displayErrors($messages)
function checkLoggedIn($status){
switch($status){
// if yes, check user is logged in:
// ie for actions where, yes, user must be logged in(!)
case "yes":
if(!isset($_SESSION["loggedIn"])){
header("Location: login.php");
exit;
}
break;
// if no, check NOT logged in:
// ie for actions where user can't already be logged in
// (ie for joining up or logging in)
case "no":
if(isset($_SESSION["loggedIn"]) && $_SESSION["loggedIn"] === true ){
header("Location: members.php?".session_name()."=".session_id());
}
break;
}
// if got here, all ok, return true:
return true;
} // end func checkLoggedIn($status)
function checkPass($nickname, $password) {
global $link;
$query="SELECT nickname, password FROM users WHERE nickname='$nickname' and password='$password'";
$result=mysql_query($query, $link)
or die("checkPass fatal error: ".mysql_error());
// Check exactly one row is found:
if(mysql_num_rows($result)==1) {
$row=mysql_fetch_array($result);
return $row;
}
//Bad Login:
return false;
} // end func checkPass($nickname, $password)
function cleanMemberSession($nickname, $password) {
$_SESSION["nickname"]=$nickname;
$_SESSION["password"]=$password;
$_SESSION["loggedIn"]=true;
} // end func cleanMemberSession($nickname, $pass)
function flushMemberSession() {
// use unset to destroy the session variables
unset($_SESSION["nickname"]);
unset($_SESSION["password"]);
unset($_SESSION["loggedIn"]);
// and use session_destroy to destroy all data associated
// with current session:
session_destroy();
return true;
} // send func flushMemberSession()
function doCSS() {
?>
<style type="text/css">
body{font-family: Arial, Helvetica; font-size: 10pt}
h1{font-size: 12pt}
</style>
<?php
} // end func doCSS()
# function validates HTML form field data passed to it:
function field_validator($field_descr, $field_data,
$field_type, $min_length="", $max_length="",
$field_required=1) {
# array for storing error messages
global $messages;
# first, if no data and field is not required, just return now:
if(!$field_data && !$field_required){ return; }
# initialize a flag variable - used to flag whether data is valid or not
$field_ok=false;
# this is the regexp for email validation:
$email_regexp="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|";
$email_regexp.="(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
# a hash array of "types of data" pointing to "regexps" used to validate the data:
$data_types=array(
"email"=>$email_regexp,
"digit"=>"^[0-9]$",
"number"=>"^[0-9]+$",
"alpha"=>"^[a-zA-Z]+$",
"alpha_space"=>"^[a-zA-Z ]+$",
"alphanumeric"=>"^[a-zA-Z0-9]+$",
"alphanumeric_space"=>"^[a-zA-Z0-9 ]+$",
"string"=>""
);
# check for required fields
if ($field_required && empty($field_data)) {
$messages[] = "$field_descr is a required field.";
return;
}
# if field type is a string, no need to check regexp:
if ($field_type == "string") {
$field_ok = true;
} else {
# Check the field data against the regexp pattern:
$field_ok = ereg($data_types[$field_type], $field_data);
}
# if field data is bad, add message:
if (!$field_ok) {
$messages[] = "Please enter a valid $field_descr.";
return;
}
# field data min length checking:
if ($field_ok && ($min_length > 0)) {
if (strlen($field_data) < $min_length) {
$messages[] = "$field_descr is invalid, it should be at least $min_length character(s).";
return;
}
}
# field data max length checking:
if ($field_ok && ($max_length > 0)) {
if (strlen($field_data) > $max_length) {
$messages[] = "$field_descr is invalid, it should be less than $max_length characters.";
return;
}
}
}
?>
login.php
<?php
include_once("config.php");
checkLoggedIn("no");
$title="Member Login Page";
if(isset($_POST["submit"])) {
//
// Check fields were filled in
//
// login must be between 4 and 15 chars containing alphanumeric chars only:
field_validator("nickname", $_POST["nickname"], "alphanumeric", 4, 15);
// password must be between 4 and 15 chars - any characters can be used:
field_validator("password", $_POST["password"], "string", 4, 15);
// if there are $messages, errors were found in validating form data
// show the index page (where the messages will be displayed):
if($messages){
doIndex();
// note we have to explicity 'exit' from the script, otherwise
// the lines below will be processed:
exit;
}
// OK if we got this far the form field data was of the right format;
// now check the user/pass pair match those stored in the db:
if( !($row = checkPass($_POST["nickname"], $_POST["password"])) ) {
// nickname/passwd string not correct, create an error message:
$messages[]="Incorrect nickname/password, try again";
}
if($messages){
doIndex();
exit;
}
cleanMemberSession($row["nickname"], $row["password"]);
// and finally forward user to members page (populating the session id in the URL):
header("Location: members.php?".session_name()."=".session_id());
} else {
// The login form wasn't filled out yet, display the login form for the user to fill in:
doIndex();
}
function doIndex() {
global $messages;
global $title;
// drop out of PHP mode to display the plain HTML:
?>
<html>
<head>
<title><?=$title?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<?php doCSS()?>
<body>
<h1><?=$title?></h1>
<?php
// if there are any messages stored in the $messages array, call the displayErrors
// function to output them to the browser:
if($messages) { displayErrors($messages); }
?>
<form action="<?=$_SERVER["PHP_SELF"]?>" method="POST">
<table>
<tr><td>Nickname:</td><td><input type="text" name="nickname"
value="<?php print isset($_POST["nickname"]) ? $_POST["nickname"] : "" ;?>"
maxlength="15"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" value="" maxlength="15"></td></tr>
<tr><td> </td><td><input name="submit" type="submit" value="Submit"></td></tr>
</table>
</form>
<a href="join.php">Signup</a> if you are not a member.
</body>
</html>
<?php
}
?>