This tutorial is aimed at creating a simple login/members area using PHP MySQL.
I will waste no time and get straight down to business. The tutorial is based on 6 easy steps.
Step 1:
Creating a table in the database.
I have created a very simple table that has only two columns; username and password.
Here is the SQL:
CREATE TABLE `userstable` (
`userName` varchar(20) NOT NULL default ”,
`password` varchar(20) NOT NULL default ”,
PRIMARY KEY (`userName`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Step 2:
Create a connection to the database. Although the file below is meant only for a database connection I have taken the liberty of using it to save some general purpose settings as well.
//dbConfig.php
<?php
/*
- The config file for the database connection and variables
- change the database name and username and password
- /
//variables for the databse connection
$serverName = “localhost”;
$userName = “manager”;
$password = “”;
$dbName = “testdatabase”;$conn = mysql_pconnect($serverName, $userName, $password);
if (!$conn)
{
//print error message, the echo command support html encodeing.
echo(’The connection to the database could not be established!’);
die(’The connection to the database could not be established!’);
}
else
{
// select the database which you wish to opereate
mysql_select_db($dbName);}
// other variable
$loginSuccess = “phpMembersArea.php”;
$RegisterSuccess = “phpRegister.php?op=thanks”;
$loginRequired = “phpLogin.php?op=loginFirst”;
$timeout = 3600;
$authenticatioMethod = “cookie”;function CheckLogin() {
// fucntion that checks if some is logged in or not
global $authenticatioMethod;
if (strcmp($authenticatioMethod ,”cookie”) == 0)//we have choosen to use cookies
{if (!isset($_COOKIE["login"]))
{
return null;
}
else
{
return $_COOKIE["login"];}
}
else// we are using session based authentication
{
if (!$_Session["userID"] || $_Session["valid_expire_time"] < time())
{
$_Session["userID"] = null;
$_Session["valid_expire_time"] = time()-1;
session_destroy();
return null;
}
else
{
return $_Session["userID"];
}
}
return null;
}
function RedirectTo($url)
{
//I have to use this function because the php function header can only be called
// if no output has been sent
// this solution uses java scripts so beware
echo(’<script type=”text/javascript”> document.location = ”.$url.”; </script>’);
}
?>
Step 3:
Create a Registeration Page.
I provide a simple registeration page, where you can enter two fields, username and password.
//phpRegister.php
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title></title>
</head>
<body>
<form action=”?op=register” method=”POST”>
Username: <input name=”userID” MAXLENGTH=”16″><br />
Password: <input type=”password” name=”password” MAXLENGTH=”16″><br />
<input type=”submit”>
</form>
<?php
// first we include the dbconfig file
// note that we do not need to open the connection
// when the file is included and this page is loaded, the code is automatically executed
echo(’hello’);
include (”dbConfig.php”);/*
- Here is the plan of action, this is the page that contains the registeration form
- also this is the page that will connect to the database and execute the insert query
- so we need to know if the page is being run from a
- /
// we suppose that a variable named op would be passed with a value
// register if there is a registeration request.
if ($_GET["op"] == “register”)
{if (!($userID = $_POST["userID"]) )
{
echo(’UserName field is missing!’);
}
else if (!($password = $_POST["password"]))
{
echo(’Password field is missing!’);
}$query = “INSERT INTO `USERSTABLE` VALUES( ‘”.$_POST["userID"].”‘, Password(’”.$_POST["password"].”‘))”;
//note that my sql requires the password filed to be casted
// also note that . is the string concatenation operator
// also not the “ around the table name$result = mysql_query($query, $conn);
//you can also redirect to a different pageif (!$result )
{
// make sure that the user was inserted
echo(’<br><h2>The user could not be inserted<br>’);
echo(’The error cant be displayed</h2>’);
}
else
{REdirectTo($RegisterSuccess);
}}
else if ($_GET["op"] == “thanks”)
{
echo(’<br><h2>The user was added successfully!</h2>’);
}
//The web form for input ability?>
</body>
</html>
After this step you have successfully created a user account. All you need to do now is to create a login page.
Step 4:
The plan of action for our login page is that we pass it an query string argument, ‘op’ that dictates what the page does. If the value of this variable is ‘login’ the page gets the POST information and tries to login.
//phpLogin.php
<?php
include (’dbConfig.php’);
if ($_GET["op"] == “login”)//check if this is a login request
{
$query = “Select * from `userstable` where `userName`=’”.$_POST["userID"].”‘ AND `password`=Password(’”.$_POST["password"].”‘) “;$result = mysql_query($query, $conn);
$obj = @mysql_fetch_object($result);
if ($obj)
{
// means sucessful login
$loginSucessful = 1;
//create session variables
// i will create both a login cookie
// and session variables
// and show how to use both for authentication$_SESSION["valid_userID"] = $_POST["userID"];
$_SESSION["valide_time"] = time();
$_SESSION["valid_expire_time"] = time()+$timeout;//set the cookies
//i create a cookie where i set the cookie information to the user name
// the userID can be encrypted also for better security.
setcookie(”login”, $_POST["userID"], time()+$timeout);// create a cookie
}
else
{
$loginSucessful = 0;
}if ($loginSucessful == 1)
{
//login has succeeded proceed to members area
if ($_GET["referrer"] )
{
// if we were sent to the login page due to some request of a members area page
// go to that page
RedirectTo($_POST["referrer"]);
}
else
{
RedirectTo($loginSuccess);
}
}
else
{
echo(’<br><h2>Login Information is not correct<br>’.$_POST["userID"].’ does not exist or password is incorrect</h2>’);
}
}
else if($_GET["op"] == “loginFirst”)
{
echo(’<br><h2>You must login first.</h2>’);
}
?>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title></title>
</head>
<body>
<?php echo(” <form action=”?op=login” method=”POST”>”); ?>
<table>
<tr>
<td>
UserID:
</td>
<td>
<input type = “text” name=”userID” maxlength=”16″></td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type = “password” name=”password” maxlength=”16″></td>
</tr>
<tr>
<td></td>
<td>
<input type =”submit” name=”subit” maxlength=”16″></td>
</tr>
</table>
</form></body>
</html>
Caution: There must be nothing before the ‘<php’ at the start of the page, if there is something the cookie would not be created. It took me some time to figure this out. Keeping this in mind can save a lot of time. Even an empty line or a space can mess things up.
PS: When a members area page is accessed without being logged in, the page redirects to the login page giving it a ‘referrer’ argument. I however could not make it work, if anyone can help please look at:
<?php echo(” <form action=”?op=login” method=”POST”>”); ?>
I was trying to replace this with
<?php echo(” <form action=”?op=login&referrer=” . $_GET["referrer"] . “” method=”POST”>”); ?>
However, whenever there was a valid referrer the username and password is not verified, the page works fine otherwise.
Step 5:
The members area page.
//phpMembersArea.php
<?php
session_start();
include (’dbConfig.php’);
$loggedInUser = CheckLogin();
if (!$loggedInUser)// no one is logged in
{
echo(’You are not logged in’);
RedirectTo(”phpLogin.php?referrer=phpMembersArea.php”);
}
else
{
echo(’<h2>Welcome ‘.$loggedInUser.’!</h2><br>’);
}
?>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title></title>
</head>
<body>
<h1>This is the members area</h1>
<br>
<br>
<a href = “phpLogout.php”>Logout</a>
<?php?>
</body>
</html>
The page calls the CheckLogin() function defined in the dbConfig.php. This function checks the cookie or the session variable for login information. If this information is found the login proceeds otherwise the user is redirected to the login page.
Step 6:
The logout page simply deletes the cookie and the session.
//phpLogout.php
<?php
setcookie(”login”, “”, time()-100);
include (’DbConfig.php’);RedirectTo(”index.php”);
?>
<!–
To change this template, choose Tools | Templates
and open the template in the editor.
–>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title></title>
</head>
<body>
</body>
</html>
And there you go, you are done.
All that can be done in mere 5 minutes with probably 2/3 lines of code with Django Framework in Python. That would be more portable, flexible, scalable, secure….
But nice post … keep it comming.
nice work
gud thing to know
I need to try this, Once Logged successfully, how i can redirect the user to web page which i created memberarea.html?
RedirectTo(”index.php”);
instead of index.php can i use memberarea.html?