1
votes

I have used a login system on my website using sessions.

This is how it looks,

<?php
session_start();

ob_start();

include 'includes/db.php';

$idadm=$_POST['idadm'];
$passadm=$_POST['passadm'];

$idadm = stripslashes($idadm);
$passadm = stripslashes($passadm);
$idadm = mysql_real_escape_string($idadm);
$passadm = mysql_real_escape_string($passadm);

$sql="SELECT * FROM admin WHERE aid='$idadm' and password='$passadm'";
$result = $conn->query($sql);

$count = $result->num_rows;

if($count == 1) {
    $_SESSION['idadm'] = $idadm;
    $_SESSION['passadm'] = $passadm;

if ($_SESSION['idadm'] == 'admin') {
    header("location:admin/index.php");
} else {
    header("location:subadmin/index.php");
}
} else {
    header("location:index.php");
}

ob_end_flush();
?>

db.php has the database credentials.

This is the code that is on top of the protected pages,

<?php
    session_start();
    if (!isset($_SESSION['idadm'])) {
        header('location:/index.php');
        die;
}
?>

The login script works fine except for one problem, logged in users can access both admin and subadmin pages.

There is only one admin user and the ID for that user in the database is 'admin'. Admin should be able to access only 'admin/index.php' and other users should be able to access 'subadmin/index.php'.

How do I modify the script to make this happen?

1

1 Answers

0
votes

So, first up, get the $_SESSION["idadm"] and $_SESSION['passadm']...

So firstly in your admin page would be this:

<?php
    session_start();
    if (!isset($_SESSION['idadm'])) {
        header('location:/index.php');
        die;
    } else {
        $username = $_SESSION["idadm"];
        $password = $_SESSION['passadm'];  // Also storing passwords in session vars is not a good idea. :/

Then open up a DB connection:

$pdo = new PDO($dsn, $DBUsername, $DBPass):
// or 
$mysqli = mysqli_connect($host, $DBUsername, $DBPass, "admin")

Then check if current username and password is there in the DB...

I am doing it in PDO:

$sth = $pdo->prepare("SELECT COUNT(*) AS number_of_users FROM table_name WHERE aid = :username AND password = :password");
$sth->bindParam(":username", $username, PDO::PARAM_STR);
$sth->bindParam(":password", hash("YOUR_HASHING_ALGO", $password), PDO::PARAM_STR); // If you have not hashed the password you can remove the hash method, but not hashing a password is a horrible idea
$result = $sth->fetch(PDO::FETCH_ASSOC);
if( (int) $result["number_of_users"] >= 1 ) {
    // yay he is an admin, do somethin'
} else {
    // nope, he is not allowed to enter, what to do with him?
}

And at last close the else block with :

}

In the connection string's you have to use your own specific credentials and DB.

Hope it helps you!