Lou
Lou

Reputation: 21

Checking if user is admin or not in PHP

I am fairly new to php and I am trying to do my school assignment but teacher just says "google it" and I seriously can't find an asnwer that works for me.

Here's my login.php (please excuse the Swedish notes in it, those are for my teacher)

<?php  //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//Sätter form värderna i variabler
$username = $_POST['username'];
$password = $_POST['password'];
//Kollar om variblerna redan finns i databasen
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";

$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//Kollar om bägge värdena är likadana i databasen och sedan skapar sessionen om de är det.
if ($count == 1){
$_SESSION['loggedin'] = 1;
$_SESSION['username'] = $username;
}else{
//3.1.3 Om värdena inte stämmer kommer ett fel medelande att skickas till användaren.
echo "Invalid Login Credentials.";
}
}
//Om han loggar in så skickas han vidare till protected.php
if ($_SESSION['loggedin'] == 1) {
header('Location: protected.php');
}else{
?>

Here's the page that is accessed after you've logged in(the protected page)

<?php

    session_start();
    require('connect.php');
    // startar sessionen så att man kan använda session variablerna
    // Inkluderar connect.php för att ansluta till databasen


    if ($_SESSION['loggedin'] != 1) {
        //Om loggedin är inte lika med 1 skickas han till första login sidan

        header('Location: index.php');
        exit;
    }

?>
<html>
<head><title>Logged in!</title></head>
<body>ASDSDFSDF<br><a href="logout.php">Log out</a><br>
<?php
    $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
    $result = mysql_query($sql); 
    $admin = mysql_fetch_array($result);
    $_SESSION['admin'] = $admin['admin'];
    if ($_SESSION['admin']) == 1 {
    echo "You are an Admin!";
    }else{
    echo "You are a normal user";
    }
?>
</body>
</html>

I don't understand how this code won't work. :/

 <?php
        $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
        $result = mysql_query($sql); 
        $admin = mysql_fetch_array($result);
        $_SESSION['admin'] = $admin['admin'];
        if ($_SESSION['admin']) == 1 {
        echo "You are an Admin!";
        }else{
        echo "You are a normal user";
        }

Upvotes: 2

Views: 9563

Answers (4)

Tiago Ribeiro
Tiago Ribeiro

Reputation: 360

Try this code:

$sql = "SELECT admin FROM user WHERE username='".$_SESSION['username']."'"; //  username='".$_SESSION['username']."'"   instead username='$_SESSION['username']'";

$result = mysql_query($sql); 
$admin = mysql_fetch_array($result); 

$_SESSION['admin'] = $admin['admin']; 
if ($_SESSION['admin'] == 1) {  // Be carefull you had if($_SESSION['admin']) == 1 {  leaving "1" outside of the if
echo "You are an Admin!"; 
}else{ 
echo "You are a normal user"; 
}

Note: Tell your teacher that is time for her to stop teaching mysql and instead teach mysqli or PDO

Upvotes: 0

moonknight
moonknight

Reputation: 334

Your code is not safe because:

  • You can be injected (mySql Injection)
  • Your password is stored as plain text

Moreover, I suggest that you use MVC pattern.

login.php:

<?php
session_start();
require("functions.php"); // file with your functions

if ($_SESSION["logged"]) // if already logged, redirect to admin page 
    header("Location: ./admin.php");
else
{
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        // logIn function in "functions.php" file, returns true if correctly logged
        $login = logIn($_POST["user"], $_POST["password"]);
        if ($login === true)
        {
            $_SESSION["logged"] = true;
            header("Location: ./admin.php");
        }
        else
        {
            // login failed, show error page

            $error = $login;
            // html code for header
            require("templates/header.php"); 

            // html code for body that will display $error
            require("templates/error_page.php"); 

            // html code for last part of the page
            require("templates/footer.php");
        }
    }
    else
    {
        // No POST request, so the user must fill the form yet

        require("templates/header.php");

        // Contains html code for login form
        require("templates/login_form.php");

        require("templates/footer.php");
    }
}
?>

functions.php (file used to store your php functions):

function logIn($username, $pass)
{
    if ($username == "" || $pass == "")
        return "Please, fill every text field.";
    $pdo = connectToServer();

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");    
    $stmt->execute(array("username" => $username));

    $fetch = $stmt->fetch();

    $numberRows = $stmt->rowCount();
    if ($numberRows > 0)
    {
        // user exists, check for password
        $crypted = hash('ripemd160', $fetch["salt"] . $pass);
        /* NOTE: you must have encrypted passwords in the same way 
           at the moment of signing up.
           Without encryption (not recommendable) you can use:
           $crypted = $pass;
        */

        if ($crypted == $fetch["pass"])
        {
            // Logged, do whatever you want and return true
            return true;
        }
        else
            return "You have inserted a wrong username or password";
     }
     else
         return "You have inserted a wrong username or password";   
}

Upvotes: 0

An Vo
An Vo

Reputation: 359

Please check again this code:

$sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";

There maybe 2 mistakes here:

  1. You cannot interpolate $_SESSION in ' ';
  2. When in quote, "$_SESSION['username']" should be change to "$_SESSION[username]";

To recap, you can use the way below:

$sql = "SELECT admin FROM `user` WHERE username='".$_SESSION['username']."'";

By this way you can keep the original method of SQL that have the quote:

WHERE username='xxx'

Upvotes: 2

Martin Gottweis
Martin Gottweis

Reputation: 2739

Don't worry about mysqli and other comments, this code works just fine for learning purposes. Here is it explained line by line:

    $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
    $result = mysql_query($sql);

Perform an sql query searching for user with username stored in session['username']. It doesn't fetch all the columns, just the admin column, which says if the user is admin or isnt.

    $admin = mysql_fetch_array($result);

This just loads the sql result into an array. If the user with the stored username is found, it will be just an array with one boolean variable: 1 or 0

    $_SESSION['admin'] = $admin['admin'];

Stores the boolean variable into session

    if ($_SESSION['admin']) == 1 {
        echo "You are an Admin!";
    }else{
        echo "You are a normal user";
    }

prints the result of the operation.

There are several caveats however. For example what happens if the username doesnt exist. If you receive some errors, please try to print out everything and send the error messages.

Upvotes: 0

Related Questions