Hi,

I have a site with a login form for users and administrators to enter their details. Anyone can show me simple code how to separate between admin login and user login because i'm new in php.I uses PHP object oriented.Anyone can show me simple tutorial and easy to understand how to do that login.

Dani AI

Generated

Good direction so far from , , @diafol, , and . A few quick fixes to your snippet, : use comparison (===) not assignment (=), match key names exactly (Admin vs admin), do not put redirects in a while loop, and always call session_start() before touching $_SESSION. Also avoid echoing JavaScript for redirects; use header('Location: ...'); then exit;.

Here is a minimal, secure flow using one table with a role field (e.g., admin or user). It uses prepared statements and password hashing. Keep only the user id and role in the session.

<?php
session_start();
// $pdo = new PDO($dsn,$user,$pass,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $u = trim($_POST['loginName'] ?? '');
    $p = $_POST['loginPass'] ?? '';

    $stmt = $pdo->prepare('SELECT id, role, password_hash FROM users WHERE username = :u LIMIT 1');
    $stmt->execute([':u' => $u]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($p, $user['password_hash'])) {
        session_regenerate_id(true);
        $_SESSION['uid'] = (int)$user['id'];
        $_SESSION['role'] = $user['role']; // 'admin' or 'user'
        header('Location: ' . ($user['role'] === 'admin' ? '/admin/dashboard.php' : '/app/home.php'));
        exit;
    }
    $error = 'Invalid username or password.';
}

Then gate pages by role (what @diafol and described as RBAC):

function requireRole(string $needed) {
    if (empty($_SESSION['role']) || $_SESSION['role'] !== $needed) {
        http_response_code(403);
        exit('Access denied');
    }
}

Hash stored passwords with password_hash and verify with password_verify. Use prepared statements (PDO::prepare) to prevent SQL injection, and enforce server-side authorization on every request to avoid broken access control (see OWASP A01:2021). (php.net)

Recommended Answers

All 12 Replies

For admin and users have you used same table in your database?

You can implement this by PHP sessions or cookies.
Learn PHP Sessions here :
http://www.tizag.com/phpT/phpsessions.php

Then you can go for implementations.
refer :


If you are using only sessions, you can differ your pages by setting one session like flag 1 for admin and 0 for users.
If you are using databases for this you differ your pages with query.

Try and implement this and post your code for help if you find any difficulties.
Thanks.

In my table i have Admin=Y for administrator and Admin=N for user.

OK then you have to use that field in session when user login as following..

$_SESSION["admin"]=$rs["admin"];

Now you can differentiate with the session. If $_SESSION["admin"]="Y" then admin login else user login

See it's just simple...once you have logged in just check the $_SESSION["admin"],if it is set then then use this:-

if(isset($_SESSION['admin']))
{
//code for admin page....or either you can also redirect him to other pages for adiminstration and maintainance purpose
}
else
{
//non-admin page or content
}
Member Avatar for Member #120589

users table should have a 'usertype' field, e.g. 0 = unconfirmed, 1 = user, 2 = moderator, 4 = admin etc. Whatever you need.

when user logs in, check the DB, get the usertype and place it in a session var as already described. This var then allows or refuses entry to certain pages, or even shows different data on a page, e.g extra nav items or sidebar quickactions etc.

users table should have a 'usertype' field, e.g. 0 = unconfirmed, 1 = user, 2 = moderator, 4 = admin etc. Whatever you need.

when user logs in, check the DB, get the usertype and place it in a session var as already described. This var then allows or refuses entry to certain pages, or even shows different data on a page, e.g extra nav items or sidebar quickactions etc.

I agree with Ardav....plus...welcome to the world of black hat bad boys :)

if(isset($_POST['Login']))
{

        $loginName = $_POST['loginName'];
        $loginPass = $_POST['loginPass'];

        if($loginName =="" || $loginPass =="")
        {
            echo "<script language='JavaScript'>alert('There is incomplete Login. Please Retry!.');window.location = '../index.php';                     </script>";
        }

        else
        {
            $Login = new Login();
            $LoginSuccess = $Login->LoginCheck($loginName,$loginPass);
            if($LoginSuccess)
            {

                $Supervisor = new Supervisor();
                $CheckSupervisor = $Supervisor->checkSupervisor($loginName);
                while($CheckSupervisor)
                {
                     If $_SESSION["Admin"]='Y'
                     {
                        echo "<script language='JavaScript'>alert('Login  as admin');window.location = '../boundary/adminMenu.php';                              </script>";
                     }
                     else
                     {
                        echo "<script language='JavaScript'>alert('Login  as user');window.location = '../boundary/supervisorMenu.php';                          </script>";
                     }
                }    
            }

          } 
}         

else 
{
    echo "<script language='JavaScript'>alert('Login Unsuccessful. Please login again!.');window.location = '../index.php';                          </script>";

}

I try to do like this but not running.anyone can help me because im new in php

$LoginSuccess = $Login->LoginCheck($loginName,$loginPass);
//..............................
$CheckSupervisor = $Supervisor->checkSupervisor($loginName);

Why will you need two classes?
Why not do something like

$LoginSuccess = $Login->LoginCheck($loginName,$loginPass);
if($Login->LoginCheck($loginName,$loginPass) && $Login->checkAdmin()){
    //Admin, do funny stuff
}else{
    //normal user
}

I personally find it easier to assign roles by using a RoleCD in the user table and then assigning different capabilities based on that RoleCD. That will prevent you from needing two separate tables while still ensuring that only Administrators/Supervisors are seeing the appropriate functions.

Just my 2 cents....;)

evstevemd is right.
and also use comparision operator in if condition instead of assignment operator.

If $_SESSION["Admin"]=='Y'

Hi,

I have a site with a login form for users and administrators to enter their details. Anyone can show me simple code how to separate between admin login and user login because i'm new in php.I uses PHP object oriented.Anyone can show me simple tutorial and easy to understand how to do that login.

http://www.daniweb.com/web-development/php/threads/370997/1597032#post1597032

I think I had a similar problem, but it was solved. Review my thread and you'll get all the files you need, I think.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.