How To make admin page with database


Account Login Details for the Demo page are:
  • User Name: swashata; Password: swashata;OR
  • User Name: admin; Password: admin
If you want to understand the coding behind the login system, then read on below…

#0: Strategy Used behind the Login System:

Here we shall use 5 files for making the whole system.file structure
  • config.php: The main file for holding the information related to the admin MySQL table. We shall discuss in brief how to create the table. For information do check the MySQL posts.
  • admin.php: For administrative functions. It will redirect to login.php if not authorized already;
  • login.php: A webpage for displaying form of login. It will submit the form to check_login.phpwhere it will be processed further;
  • check_login.php: A PHP script to check the login details from the MySQL Table. If successfully matched, then it will register the Session, else will redirect back to the login.php file with error message;
  • logout.php: It will delete the session, and will redirect back to login.php file with success message;

#1: Setting up the MySQL Table:

We shall use a MySQL table like this for storing administrator information:
iduser_nameuser_pass
1adminadmin
2swashataswashata
Basically we shall encrypt the password inside the table. Just for the demonstration I have showed the passwords above…
Now create a Database and inside it create a table login_admin with the following MySQL query command:
?
1
2
3
4
5
6
7
CREATE TABLE login_admin
(
id INT NOT NULL AUTO_INCREMENT,
user_name VARCHAR(100),
user_pass VARCHAR(200),
PRIMARY KEY (id)
)
Now insert the two user information inside the table with the following command:
?
01
02
03
04
05
06
07
08
09
10
11
INSERT INTO login_admin (user_name, user_pass)
VALUES
(
‘swashata’, SHA(‘swashata’)
)
INSERT INTO login_admin (user_name, user_pass)
VALUES
(
‘admin’, SHA(‘admin’)
)
Now your MySQL table is ready for use!

#2: Setting up the config.php file:

As mentioned before, it just contains all the necessary MySQL Database connection information. Here is the code for this file:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
<?php
/**********************************************************************
 *Contains all the basic Configuration
 *dbHost = Host of your MySQL DataBase Server... Usually it is localhost
 *dbUser = Username of your DataBase
 *dbPass = Password of your DataBase
 *dbName = Name of your DataBase
 **********************************************************************/
$dbHost = 'localhost';
$dbUser = 'Data Base User Name';
$dbPass = 'Data Base Password';
$dbName = 'Data Base Name';
$dbC = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName)
        or die('Error Connecting to MySQL DataBase');
?>
Just save this file with the above codes.

#3: Code behind the login.php File:

It shows up the login form and moves it to check_login for further processing!
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Login Demo</title>
</head>
<body>
<?php
    $login_form = <<<EOD
<form name="login" id="login" method="POST" action="check_login.php">
<p><label for="username">Please Enter Username: </label><input type="text" size="100" name="username" id="username" value="Enter Username here" /></p>
<p><label for="password">Please Enter Password: </label><input type="password" size="40" name="password" id="password" value="abracadabra" /></p>
<p><input type="submit" name="submit" id="submit" value="Submit"/> <input type="reset" name="reset" id="reset" value="reset"/></p>
</form>
EOD;
$msg = $_GET['msg'];  //GET the message
if($msg!='') echo '<p>'.$msg.'</p>'; //If message is set echo it
echo "<h1>Please enter your Login Information</h1>";
echo $login_form;
?>
</body>
</html>
The $msg variable is used to show any message to the user using GET method.

#4: Code Behind the check_login.php file:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file
$username = $_POST['username']; //Set UserName
$password = $_POST['password']; //Set Password
$msg ='';
if(isset($username, $password)) {
    ob_start();
    include(DOC_ROOT.'/config.php'); //Initiate the MySQL connection
    // To protect MySQL injection (more detail about MySQL injection)
    $myusername = stripslashes($username);
    $mypassword = stripslashes($password);
    $myusername = mysqli_real_escape_string($dbC, $myusername);
    $mypassword = mysqli_real_escape_string($dbC, $mypassword);
    $sql="SELECT * FROM login_admin WHERE user_name='$myusername' and user_pass=SHA('$mypassword')";
    $result=mysqli_query($dbC, $sql);
    // Mysql_num_row is counting table row
    $count=mysqli_num_rows($result);
    // If result matched $myusername and $mypassword, table row must be 1 row
    if($count==1){
        // Register $myusername, $mypassword and redirect to file "admin.php"
        session_register("admin");
        session_register("password");
        $_SESSION['name']= $myusername;
        header("location:admin.php");
    }
    else {
        $msg = "Wrong Username or Password. Please retry";
        header("location:login.php?msg=$msg");
    }
    ob_end_flush();
}
else {
    header("location:login.php?msg=Please enter some username and password");
}
?>
As you can see it registers $_SESSION['name'] superglobal variable along with session_register and then redirects to admin.php. Now lets see what the admin.php file has to protect it from unauthorized use! Also note that if username and password do not match, then it redirects back to thelogin.php file with an error $msg.

#5: Code behind admin.php file:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<?php
session_start(); //Start the session
define(ADMIN,$_SESSION['name']); //Get the user name from the previously registered super global variable
if(!session_is_registered("admin")){ //If session not registered
header("location:login.php"); // Redirect to login.php page
}
else //Continue to current page
header( 'Content-Type: text/html; charset=utf-8' );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Welcome To Admin Page Demonstration</title>
</head>
<body>
    <h1>Welcome To Admin Page <?php echo ADMIN /*Echo the username */ ?></h1>
    <p><a href="logout.php">Logout</a></p> <!-- A link for the logout page -->
    <p>Put Admin Contents</p>
</body>
</html>
I have put comments every where! So you will be able to easily understand the code! Basically, here you need to be creative to put the admin contents properly! What ever it is, it will only be shown to authorized users. Also we have set a constant ADMIN to fetch the username from the super global variable $_SESSION[‘name’] and we can echo it where ever we want!

#6: Logging out with logout.php

It is used to destroy the current session. It is very simple!
?
1
2
3
4
5
<?php
session_start(); //Start the current session
session_destroy(); //Destroy it! So we are logged out now
header("location:login.php?msg=Successfully Logged out"); // Move back to login.php with a logout message
?>
Save the file with the above code and you are done!

0 ulasan: