0

This is my code for a user login. It allows the user to login fine.

What do i need to add to the code to allow admin users to be able to login and then be redirected to another page?

In the database I have assigned 0 to the normal users and 1 to the admin users.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<?php
    require('databaseConnect.php');
    session_start();
    // When a form is submitted it will insert the values into my database.
    if (isset($_POST['username'])){
        $username = $_POST['username'];
        $password = $_POST['password'];
    //Checking is user existing in the database or not
        $query = "SELECT * FROM `Test` WHERE username='$username' and password='".md5($password)."'";
        $result = mysql_query($query) or die(mysql_error());
        $rows = mysql_num_rows($result);
        if($rows==1){
            $_SESSION['username'] = $username;
            header("Location: index.php"); // This will redirect the user to index.php page. 
            }else{
                echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
                }
    }else{
?>
<div class="testbox">
<img src="MorleyWasteLogo.png" alt="Logo" align="middle" style="width:340px;height:90px;" >
<h1>Login</h1>
<form action="" method="post" name="login">
<label id="icon" for="name"><i class="icon-user"></i></label>
<input type="text" name="username" id="name" placeholder="Username" required/>
<label id="icon" for="name"><i class="icon-shield"></i></label>
<input type="password" name="password" id="name" placeholder="Password" required/>
<input name="submit" type="submit" value="Login" />
<input type="reset" value="Reset"/>
<a href='registration.php'>Register Here</a>
</form>
</div>
<?php } ?>
</body>
</html>
2
Contributors
1
Reply
19
Views
1 Year
Discussion Span
Last Post by cereal
0

Hi,

after if($rows==1){ fetch the row and check the column value that defines the role, use an IF statement to define the session and redirect, something like:

if($rows==1)
{
    mysql_data_seek($result, 0);
    $row = mysql_fetch_assoc($result);

    # admin
    if($row['role'] == 1)
    {
        $_SESSION['role'] = 1;
        header("Location: /admin/");
        exit;
    }

    # user
    $_SESSION['role'] = 0;
    header("Location: /");
    exit;
}

Make sure, on admin side to check the session value, otherwise a simple user could access the restricted area.

Also, switch to MySQLi or PDO, the MySQL api is now removed in PHP 7:

Edited by cereal

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.