PHP Multiple Login Form - Navigating to different pages based on login credentials

I am trying to create a login page that will send the user to another index.php page based on their credentials. For example, if a user with the role "IT technician" logs in, they will be sent to "index.php", and if a user with the role "Student" logs in, they will be sent to "student / index" .php ".

I can't see what is wrong with my code, but it doesn't work ... I get an "invalid credentials" message every time I press the login button.

My code for the user login page is here:

<?php
session_start();
if (isset($_SESSION["manager"])) {
header("location: http://www.zuluirminger.com/SchoolAdmin/index.php");
exit();
}
?>

<?php
if (isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["role"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]);
$role = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["role"]);
include "adminscripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM Users WHERE username='$manager' AND password='$password' AND role='$role' LIMIT 1");
$existCount = mysql_num_rows($sql);
if (($existCount == 1) && ($role == 'IT Technician')) {
    while ($row = mysql_fetch_array($sql)) {
        $id = $row["id"];
    }
    $_SESSION["id"] = $id;
    $_SESSION["manager"] = $manager;
    $_SESSION["password"] = $password;
    $_SESSION["role"] = $role;
    header("location: http://www.zuluirminger.com/SchoolAdmin/index.php");
} else {
    echo 'Your login details were incorrect. Please try again <a href="http://www.zuluirminger.com/SchoolAdmin/index.php">here</a>';
    exit();
}
}
?>

<?php
if (isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["role"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]);
$role = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["role"]);
include "adminscripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM Users WHERE username='$manager' AND password='$password' AND role='$role' LIMIT 1");
$existCount = mysql_num_rows($sql);
if (($existCount == 1) && ($role == 'Student')) {
    while ($row = mysql_fetch_array($sql)) {
        $id = $row["id"];
    }
    $_SESSION["id"] = $id;
    $_SESSION["manager"] = $manager;
    $_SESSION["password"] = $password;
    $_SESSION["role"] = $role;
    header("location: http://www.zuluirminger.com/SchoolAdmin/student/index.php");
} else {
    echo 'Your login details were incorrect. Please try again <a href="http://www.zuluirminger.com/SchoolAdmin/index.php">here</a>';
    exit();
}
}
?>

      

The form from which the data is being pulled is displayed here:

<form id="LoginForm" name="LoginForm" method="post" action="http://www.zuluirminger.com/SchoolAdmin/user_login.php">
  User Name:<br />
  <input type="text" name="username" id="username" size="50" /><br />
  <br />

  Password:<br />
  <input type="password" name="password" id="password" size="50" /><br />
  <br />

  Log in as:
  <select name="role" id="role">
    <option value="">...</option>
<option value="Head">Head</option> 
<option value="Deputy Head">Deputy Head</option> 
<option value="IT Technician">IT Technician</option> 
<option value="Pastoral Care">Pastoral Care</option> 
<option value="Bursar">Bursar</option> 
<option value="Secretary">Secretary</option> 
<option value="Housemaster">Housemaster</option> 
<option value="Teacher">Teacher</option> 
<option value="Tutor">Tutor</option> 
<option value="Sanatorium Staff">Sanatorium Staff</option> 
<option value="Kitchen Staff">Kitchen Staff</option> 
<option value="Parent">Parent</option> 
<option value="Student">Student</option>
</select><br />
  <br />

  <input type="submit" name = "button" id="button" value="Log In" onclick="javascript:return validateLoginForm();" />
  </h3>
</form>

      

Once logged in (and if the correct page is loaded, the validation code I have at the top of the script looks like this:

<?php
session_start();
if (!isset($_SESSION["manager"])) {
header("location: http://www.zuluirminger.com/SchoolAdmin/user_login.php");
exit();
}

$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]);
$role = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["role"]);

include "adminscripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM Users WHERE username='$manager' AND password='$password' AND role='$role' LIMIT 1");
$existCount = mysql_num_rows($sql);
if ($existCount == 0) {
header("location: http://www.zuluirminger.com/SchoolAdmin/index.php");
exit();
}
?>

      

As you know, a database table has the following fields: id , username , password, and role .

Any help would be greatly appreciated!

Thanks a lot, Zulu

+3


source to share


3 answers


This is a classic debugging situation in which you can temporarily output intermediate data, see what is going wrong. There are several improvements you can make to your code to make this easier.

  • On the main login page, you connect to the database twice SELECT

    and filter the input twice and twice. It is not necessary. Reduce this to one block - it will make your code much more compact.
  • Instead of putting the code in mysql functions, I think this is better:

    $sql = "
        SELECT id FROM Users
        WHERE
            username='$manager'
            AND password='$password'
            AND role='$role'
        LIMIT 1
    ";
    //echo $sql; exit();
    mysql_query($sql);
    
          

Now you can uncomment the line echo

and see if the SQL is correct. Run it with the database manually to check and then delete it when you are happy.



  • Also see how did I inject the SQL string? This is much more understandable.
  • Use header('Location: ...')

    i.e. uppercase 'L'. Your path will work, but this path is more correct.
  • After redirecting, always do exit()

    . This is because PHP will continue to run the script normally until the server realizes that the user is offline and you want to be kind to your server :)

    .
  • You don't need to redirect the full code url. Perfectly redirect to "/SchoolAdmin/index.php"

    , which will save you the harsh posting of your website address.
  • You don't need to check all $_POST

    vars before you do a database operation. It's easy for this:

    if ($_POST) {
        // Form operation
    }
    
          

A lot of neat and does the same!

  • Addendum: Instead of referencing values ​​such as "IT technician" in your code, use define('ROLE_IT_TECH', 'IT Technician');

    in the general include file. You can then refer to it in your login and in the login form, so you know you always use the same value in all use cases.
  • Addendum 2: use include_once

    , not include

    , so PHP ignores any duplicate include statements.
+3


source


You have to rebuild your if () statement where you check for successful login:

if (($existCount == 1) && ($role == 'IT Technician'))

      

The problem is that if you are not logged in with the correct credentials and the role of the IT Pro, you will see the "Invalid Login" link. You will never receive a Code for a Student or any other role.



One thing you can do is split the validation into $ existCount and $ role. Make sure they are logged in correctly. If they are, then use a set of if () elseif () or select / case statements to determine which one $ role they redirect to the appropriate page

pseudocode

if ($existCount == 1) {

    if($role == 'IT Technician') {
        header(location1);
    }
    elseif($role == 'Student') {
        header(location2);
    }
    elseif(etc...) {
        header(location3);
    }
}

      

+2


source


You hit this section every time your code runs because you do if else

if (($existCount == 1) && ($role == 'IT Technician')) {
}
else {
     echo 'Your login details were incorrect. Please try again <a href="http://www.zuluirminger.com/SchoolAdmin/index.php">here</a>';
exit();
}

      

Every time your code runs and your role is not an IT Pro, you submit an error and terminate the application entirely ... whether it is a student, a warthog or not.

While there is much room for improvement, initially I would suggest deleting the duplicated sections (IT Adminstrator vs Student) and restoring the row from the database instead, rather than letting the user submit it.

SELECT id FROM Users WHERE username='$manager' AND password='$password' LIMIT 1

if ( count($sql) == 1 ) {
     if ( $sql['role'] == 'IT Adminstrator' ) {
          header('admin_url.php');
     } elseif ( $sql['role'] == 'Student' ) {
          header('student_url.php');
     };
};

      

+2


source







All Articles