1

I have a database table that holds a users username, password and other information as well as whether theyre and administrator or not. Its currently set to Char where A is for admin and U is for normal user.

I have the following code which checks if a user exists:

<?php
session_start(); // Starting Session
include_once('config.php');

$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if(mysqli_num_rows($result) == 1) {
header("Location: home.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css"> 
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>

</head>
<body>

<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span> 
</div>

<div id="login">
  <div id="triangle"></div>
  <h1>Log in</h1>
  <form action = "" id = "logregform" method = "POST">
    <p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
    <input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
    <input type="password" placeholder="Password" name = "pass" required/>
    <input type="submit" value="Log in" name = "submit" />
    <br>
    <br>
    <p id ="bklg">Dont have an account? <a href="register.php">Sign up</a></p> 
  </form>
</div>

</html>

How would i check if Account_Type is A and if so direct the user to another page instead of the normal home.php page?

EDIT: It works fine however the admin wont log in. Ive given it test username of 456 and a password of 456 when i enter them into the two textboxes nothing happens, the screen just refreshes and im back on the login page:

new code below:

      <?php
session_start(); // Starting Session
include_once('config.php');

$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
    //set the session variables
    $_SESSION['Username'] = $row['Username'];
    $_SESSION['Account_Type'] = $row['Account_Type'];

    if ($row['Account_Type'] === 'A')  {
        header ("location: adminHome.php");
        exit;
    } else {
        header ("location: home.php");
        exit;
    }
} else {
    $error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css"> 
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>

</head>
<body>

<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span> 
</div>

<div id="login">
  <div id="triangle"></div>
  <h1>Log in</h1>
  <form action = "" id = "logregform" method = "POST">
    <p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
    <input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
    <input type="password" placeholder="Password" name = "pass" required/>
    <input type="submit" value="Log in" name = "submit" />
    <br>
    <br>
    <p id ="bklg">Dont have an account? <a href="register.php">Sign up</a></p> 
  </form>
</div>
<script>

$('#toggle-login').click(function(){
  $('#login').slideToggle('fast'); 
});
</script>
</html>
Spud91
  • 69
  • 3
  • 12

2 Answers2

1

You are going about this the wrong way. Every page that requires the user to be authenticated should check at the very start if the user is authenticated and at what level. The way to do that is to use the session.

Right now you are setting the session variable before you even check whether the user / password combination is correct so you are effectively logging in anybody who enters a username.

You need to store the variables in the session only upon successful login and as mentioned you need to get a row from your result set to get the user information:

// Personally I would use a prepared statement here
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
    // Now you can set the session variables
    $_SESSION['Username'] = $row['Username'];
    $_SESSION['Account_Type'] = $row['Account_Type'];
    // Add any additional user information to the session that you might need later on

    if ($row['Account_Type'] === 'A')  {
        header ("location: adminHome.php");
        exit;
    } else {
        header ("location: home.php");
        exit;
    }
} else {
    $error = "Username or Password is invalid";
}

Now in every page where a user is required you can do:

session_start();
if (isset($_SESSION['Username']))
{
  // valid user, additional checks for user type?
}
else
{
  // not a valid / logged in user
}

Note:

Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132
  • Ive changed my original code however i still get the same problem where when the Admin tries to login all i get is a page refresh. the username and password for the admin have been set to 456 for testing purposes, but thaty doesnt seem to work. The normal user can login perfectly fine – Spud91 Mar 24 '15 at 18:26
  • @Spud91 So get rid of the redirects and add `var_dump()`'s of your variables at different places to see where it goes wrong. – jeroen Mar 24 '15 at 18:28
  • Not sure how to do Var_Dumps. and still not letting me login as an admin. i type in the username and password. click submit. and it instantly says "Username or Password is invalid" – Spud91 Mar 24 '15 at 18:42
  • @Dharman Yes, like I mentioned in the comment above the code in my answer of 4 years ago :-) – jeroen Jun 28 '19 at 17:16
  • Yes, I see it stands out very clearly... Personally I would add a huge bold message at the top of your post, not in the code comments or even better edit the code to use prepared statements as you yourself suggested. – Dharman Jun 28 '19 at 17:18
  • @Dharman I normally would as well, but as the OP is using `mysqli_real_escape_string()` for all values, that seems a bit out of place here... – jeroen Jun 28 '19 at 17:21
  • For one, your codes doesn't, but more importantly `mysqli_real_escape_string` does not prevent SQL injections. Writing proper code in answers is never out of place. Using prepared statements is not a matter of personal preference, it is the proper way to perform SQL queries with data. – Dharman Jun 28 '19 at 17:23
  • @Dharman You do realize that I only copied what was relevant for my answer, right? And properly escaping the values is perfectly fine, although - like I mentioned in the answer - I would use a prepared statement. – jeroen Jun 28 '19 at 17:27
  • [Is "mysqli_real_escape_string" enough to avoid SQL injection or other SQL attacks?](https://stackoverflow.com/q/32391315/1839439) – Dharman Jun 28 '19 at 17:29
  • [How can I prevent SQL injection in PHP?](https://stackoverflow.com/q/60174/1839439) – Dharman Jun 28 '19 at 17:29
  • Escaping data is legacy from 15-20 years ago when there were no native prepared statements. It was just a hack/workaround to solve temporarily a problem, but it was flawed. In 2015 or in 2019 no one should encourage or even insinuate that escaping is perfectly fine. Only prepared statements with data binding are acceptable! – Dharman Jun 28 '19 at 17:32
  • @Dharman Maybe you should focus your energy on the cases where there actually is an sql injection problem. Some boundary cases with obscure character sets - which might also result in sql injection using a PDO prepared statement - don't really help your case. – jeroen Jun 28 '19 at 17:39
0
$row = mysqli_fetch_array($result);
if ($row['Account_Type'] === 'A')  {

} elseif ($row['Account_Type'] === 'U') {

} else {

}
Jaime
  • 1,402
  • 7
  • 15