More simply, if you use pure PHP, you can do this:
session_start();
if (empty($_SESSION['admin'])) {
return header('location: login.php');
}
The empty
will already evaluate whether the value of admin
exists and at the same time whether it is a boolean. If it is false and / or if it does not exist, the user will be redirected to login page (or any other page you want to redirect);
Note : Because of the critical comments regarding the use of empty
, I clarify: I do not use isset
because it would generate unnecessary code and would not apply to the case. >
Using the empty
function, we deal with two problems at the same time: The person's case is not logged, ie the $_SESSION['admin']
variable does not exist; And the case of the variable has value false
, because in this case empty
returns false
for values of type false
- and if the user is not admin can not see the page.
I would use isset
only to handle two different types of cases.
For example: differentiate unlogged user from logged in user who is not admin.
session_start();
if (! isset($_SESSION['admin']) {
return header('location: pagina_de_usuario_nao_logado.php');
} elseif (isset($_SESSION['admin']) && $_SESSION['admin'] == false) {
return header('location: pagina_de_logado_mas_nao_eh_admin.php');
}
If I used the same form I used in the first example, dealing with isset
, the code would have to look like this:
if (! isset($_SESSION['admin']) || $_SESSION['admin'] == false) {
// ...
}
See how it would be unnecessary to use isset
, if we were to replace the first form.