'Redirect to wrong page
Can anyone help me here? Thank you! Issue: In Admin page, it redirect to Student Account when I access login page. It must be redirected to its own page(admin page). role 1 = admin role 2 = student account
//Session for admin page
if(!isset($_SESSION['role']) == 1){
header("location: index.php");
die();
}
//Session for student page
if(!isset($_SESSION['role']) == 2){
header("location: index.php");
die();
}
Solution 1:[1]
Code actually needs to be understood. Looking at your condition:
if(!isset($_SESSION['role']) == 1)
...when translated to plain language, it reads:
if session role is not isset (= notset),
make a loose comparison of the "notset" result (= true or false)
with a positive integer (1 or 2).
This is clearly a nonsensical statement when "read out loud". You would have to separate your "is set" from your "is something" into two separate evaluations. (N.B. In a bool-to-integer comparison, any non-zero integers are coerced to boolean values and evaluate as true.)
Further, in your code, you redirect to the same index.php page, with no query parameters set, regardless of the outcome of your condition. This makes the conditional logic moot. You would have to redirect to unique destinations that reflect the result of your evaluation.
That said, you could for example do something like this instead:
// set a default role if none defined:
$_SESSION['role'] ??= 0;
// map roles to destinations:
$page = match($_SESSION['role']) {
1 => 'admin.php',
2 => 'student.php',
default => 'index.php'
};
// goto where they should:
header("Location: {$page}");
exit;
No isset or other conditional evaluation. No code repetition. Easy to extend for future roles. Quite readable. (If you're not on PHP 8, use switch instead.)
Please take the time to spell out to yourself the intended application logic -- state it in plain language. See if what you're saying makes any sense. Then, when you code it out, understand the "translation" of the code you have written (or copied). Ensure that it matches your original "declaration" of the logic that should be executed.
When you gain more programming experience, you will "think in code" as your second language, and have little need to spell out "mental pseudo-code". For a beginner though, this practice is much recommended to ensure that you produce sensible expressions. Good luck and don't forget your friend the manual. Familiarity with standard reference is not optional.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
