Reputation: 191
So being a newb at PHP still, I'm trying to figure out a way that I can get certain users to their respective pages.
For example I would want the admin (once logged in) to be redirected to their admin page and no one else should see this page but the admin, as well as a tutor who should be redirected to their tutor page and no one else can see this but the tutor.
Unfortunately I cannot seem to wrap my mind around how to make this work as such and I have looked around to see other examples a lot of it not relating to what I am looking for as a lot of it is about "permissions".
Here is my code for the login page:
<?php
//error_reporting(0);
error_reporting(-1);
ob_start();
session_start();
//connection to the database
require 'connection.php';
if (!empty($_POST['username']) && !empty($_POST['password']))
{
//query the databse for these columns in the table users
$records = $conn->prepare('SELECT id, Username, Password, Role FROM users WHERE Username = :username');
$records->bindParam(':username', $_POST['username']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
//var_dump($results);
// Count the results in the table if they are greater than 0
// check the hashed password on the form and the password in the db match
if((count($results) > 0) && password_verify($_POST['password'], $results['Password'])) {
//die('We have a log in');
if ($results == 'Admin'){
header('Location: adminPage.php');
} else if ($results == 'Tutor'){
header('Location: tutorPage.php');
} else {
header('Location: studentPage.php');
}
} else {
//echo $_POST['password'];
die('That user doesn\'t exist');
}
}
?>
And after trying to execute the code of course some errors will follow:
[:error] [pid 1797] [client 127.0.0.1:37161] PHP Parse error: syntax error, unexpected '''' (T_CONSTANT_ENCAPSED_STRING) in /apps/bla/web/login.php on line 31, referer: http://hinat.local/loginPage.php
What do I need to take into consideration when trying to do this or what is the simplest way that I could go about this?
Upvotes: 1
Views: 531
Reputation: 94672
You need to address the $results['Role']
as an array when testing the role, also it is a good idea to add an exit;
after a header('Location: ....);
as the header command does not stop code execution.
if((count($results) > 0) && password_verify($_POST['password'], $results['Password'])) {
//die('We have a log in');
if ($results['Role'] == 'Admin'){
header('Location: adminPage.php');
exit;
} else if ($results['Role'] == 'Tutor'){
header('Location: tutorPage.php');
exit;
} else {
header('Location: studentPage.php');
exit;
}
} else {
//echo $_POST['password'];
die('That user doesn\'t exist');
}
Upvotes: 1