This is how I would had created PHP with MySQL Database. A Short Tutorial for everyone.
we will first create a login script. The login script will have a MYSQL table which it will reference to verify the existence of a user at login. It will also have various scripts that will help register a new user and retrieve forgotten passwords.
Login ScriptThe login script will have the following pages:
- Login.php - Enables users to log in.
- Logout.php - Enables logging out.
- Register.php - Creates new users.
- Password.php - Password recovery.
- Messages.php - Handles error messages.
Let's create a table that will gather the following information about a user:
- Username
- Password>
- Level
- Admin - This will be the moderator of the system
- Normal - Normal access rights
- Date_joined
- IP Address - Enables us to identify and ban users.
- Email - Used for password recovery.
- Isbanned - Enable us to ban users
Here's the table:
CREATE TABLE `user` (
`id` int(5) NOT NULL auto_increment,
`uname` varchar(98) NOT NULL default '',
`pw` varchar(98) NOT NULL default '',
`email` varchar(100) NOT NULL default '',
`date_joined` datetime NOT NULL default '0000-00-00 00:00:00',
`ip` varchar(20) NOT NULL default '',
`level` varchar(10) NOT NULL default '',
`isbanned` enum('yes','no') NOT NULL default 'no',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=11 ;As you can see from the table layout, the table gathers a lot of information about a user. The most significant item of them all is the "isbanned" field. This field is responsible for checking whether or not a user is banned. The "ip" field stores the IP address of the user, which will be used to reinforce the isbanned status of a user.
If you can simply just copy and paste the following code from above to php my admin and run the SQL.
2) Login.php
This file displays a form that requests your username and password and also gives you the options to register as a new user or recover your password if you've forgotten it. Once you've pressed the submit button the following code gets executed:
<?
session_start();
if(isset($_GET['reg'])){
$reg=$_GET['reg'];
}else{
$reg="";
}
if($reg==1){
$msg1="<font color="#FF0000"><b>Your details have been added,
please login</b></font>";
}elseif($reg==2){
$msg1="<font color="#FF0000"><b>You have been successfully
logged out.</b></font>";
}elseif($reg==3){
$msg1="<font color="#FF0000"><b>You have been redirected because you need to be logged on as administrator.</b></font>";
}
if(isset($_POST['submit'])){
if( empty($_POST['uname']) && (empty($_POST['upass']))){
header( "Location:Messages.php?msg=1" );
exit();
}
//transfer to shorter var
$n=$_POST['uname'];
$p=$_POST['upass'];
//connect to db
include('config.php');
$query="select * from user where uname='$n' and pw='$p'";
if($result=mysql_query($query)){
$row=mysql_fetch_assoc($result);
//check each var
if($n !=$row['uname']){
header( "Location:Messages.php?msg=2" );
exit();
}
if($p !=$row['pw']){
header( "Location:Messages.php?msg=11" );
exit();
}
if($row['isbanned']=='yes'){
header( "Location:Messages.php?msg=12" );
exit();
}
}//ifresult
//put in session vars
$_SESSION['level'] = $row['level'];
$_SESSION['status'] = 'logged';
$_SESSION['username'] = $n;
//This takes you to the admin pages; change this to take you to
wherever you want it //to go.
header("location:../admin/main.php");
exit;
}?>This script checks to see whether a user exists. If so, the username and password is compared with the information in the database. It also checks to see whether the user is banned. If all the checks are okay, the script puts the username in a session variable and then sends the user through to the appropriate page. If the user does not exist, the program goes to the messages page and displays an error message.
The script also checks the user's banned status. If a user is banned, then the script directs you to the Messages page. The submitted username and password is checked individually and then the appropriate action is taken. This enables the user to know exactly which of the two, username or password, is wrong.
3) Logout.php
Logs a user out with the following code:
<?
session_start();
if($_SESSION["status"]="logged") {
session_unset();
session_destroy();
header( "Location:login.php?reg=2" );
exit();
}
else{
if ($_SESSION["status"]="not logged") {
//the session variable isn't registered, the user shouldn't even
be on this page
header( "Location:login.php" );
exit();
}
}
?>The 'header( "Location:login.php?reg=2" ); ' code sends a reg value of 2 to the login.php page, which informs the user that he/she has been logged out. To log out a user, we simply empty the session variables that have been filled at login. This is done by the session_unset() and session_destroy() functions.
4) Register.php
This script registers or adds a new user.
The following code does the job:
<?
if(isset($_POST['Submit'])){
//NEED TO CHECK IF FIELDS ARE FILLED IN
if( empty($_POST['name']) && (empty($_POST['email']))){
header("Location:Messages.php?msg=3");
exit();
}
if( empty($_POST['pw1']) && (empty($_POST['pw2']))){
header( "Location:Messages.php?msg=4" );
exit();
}
$name=$_POST['name'];
$email=$_POST['email'];
$pw1=$_POST['pw1'];
$pw2=$_POST['pw2'];
if("$pw1" !== "$pw2" ){
header( "Location:Messages.php?msg=5" );
exit();
}
$ip = $_SERVER['REMOTE_ADDR'];
if(empty($ip)){
header("location:Messages.php?msg=13");
exit();
}
if(isset($_POST['select'])){
$level=$_POST['select'];
}else{
$level="Normal";
}
//connect to the db server , check if uname exist
include('config.php');
$query=("Select * from user where uname='$name'");
$result= mysql_query($query);
$num=mysql_num_rows($result);
if ($num > 0) {//Username already exist
header( "Location:Messages.php?msg=6" );
exit();
}else{
//if username does not exist insert user details
$query=( "INSERT INTO user (uname, pw,email,date_joined,ip,level,isbanned) VALUES ('$name',password
('$pw1'),'$email',NOW(),'$ip','$level','no')");
if(!@mysql_query ($query)) {
echo mysql_error();
}else{
if(empty($_POST['select'])){
header("location:login.php?reg=1");
exit;
}else{
header("location:../admin/main.php");
exit;
}
}
}
mysql_close();
}?>The script does three things:
- Checks whether all the fields are filled in. If not, the program goes to the messages page where the appropriate error is displayed.
- Checks whether the username already exists. If so, the program goes to the messages page where the appropriate error is displayed.
- If the username does not exist, the script adds the user details and goes straight to the login page. Where the user can now login.
5) Password.php
This script sends the password that the user has forgotten to his/her email address.
Here's the password code:
<?
include("fns.php");
include "config.php";
if(isset($_POST['Submit'])){
//1. Check if form fields are filled in
if(!filledin($_POST)){
header( "Location:Messages.php?msg=7" );
exit();
}
$name=$_POST['name'];
$em=$_POST['mail'];
//2. Check if entered name exist
$query="Select pw from user where uname='$name'" or die(mysql_error());
$result= mysql_query($query);
if(mysql_num_rows($result)>0){
for ($i=0; $i<mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
$pass=$row['pw'];
$to="$emrn";
$from="From: Admin@jacquesnoah.co.ukrn";
$msg="Password:$passrn";
$msg .="Username:$namern";
$msg .="Please change your password as soon as you logonrn";
$subject="From Admin re:Your Login Passwordrn";
}
}else{
header( "Location:Messages.php?msg=8" );
exit();
}
//3. Send password to user
if(mail($to,$subject,$msg,$from)){
header( "Location:Messages.php?msg=9&email=<?php echo $em; ?>" );
exit();
//echo "Please click here to log";
}else{
header( "Location:Messages.php?msg=10");
exit();
}
}
?>This code does three things:
- Checks to see if all fields are filled in. Notice the use of the function called 'filledin()' in the line "if(!filledin($_POST)){}">. That function is declared in the functions script called "fns.php" which is included in at the top of the code. It just checks whether all posted variables contain something.
- Checks to see if entered name exists. This provides us with extra security, by checking whether the username and email address exist.
- Once all security checks have been passed, it sends the password.
I have tried and successfully able to run a effective login script. It can of course always be improved, but for now it is adequate, security wise.
Thanks.