How to redirect 2 users from different homepage using php

Issue

I want to redirect users where if users role is trainees they will go to = trainees/index.php
if admin then admin/index.php

login.php code

<?php
include("php/dbconnect.php");

$error = '';
if(isset($_POST['login']))
{

$username =  mysqli_real_escape_string($conn,trim($_POST['username']));
$password =  mysqli_real_escape_string($conn,$_POST['password']);

if($username=='' || $password=='')
{
$error='All fields are required';
}

$sql = "select * from user where username='".$username."' and password = '".md5($password)."'";

$q = $conn->query($sql);
if($q->num_rows==1)
{
$res = $q->fetch_assoc();
$_SESSION['rainbow_username']=$res['username'];
$_SESSION['rainbow_uid']=$res['id'];
$_SESSION['rainbow_name']=$res['name'];
$_SESSION['rainbow_role']=$res['role'];
echo '<script type="text/javascript">window.location="index.php"; </script>';

}else
{
$error = 'Invalid Username or Password';
}

}

?>

Solution

javascript is not really needed here, you can use header("Location: .."); to redirect the page

if ($q->num_rows == 1)
{
    $res = $q->fetch_assoc();
    $_SESSION['rainbow_username'] = $res['username'];
    $_SESSION['rainbow_uid'] = $res['id'];
    $_SESSION['rainbow_name'] = $res['name'];
    $_SESSION['rainbow_role'] = $res['role'];
    if ($res['role'] == 'trainees')
    {
        header("Location: trainees/index.php");
    }
    elseif ($res['role'] == 'admin')
    {
        header("Location: admin/index.php");
    }
    else
    {
        header("Location: member.php");
    }
    // stop php execution
    exit();
}
else
{
    $error = 'Invalid Username or Password';
}

Answered By – uingtea

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published