More simply, if you use pure PHP, you can do so:
session_start();
if (empty($_SESSION['admin'])) {
return header('location: login.php');
}
The empty
will already assess whether the value of admin
exists and at the same time whether he is a boolean. If it is false and/or if it does not exist, the user will be redirected to the login page (or any other one that you want to redirect);
Note: Because of the critical comments regarding the use of empty
, I make a clarification: I do not use the isset
because it would generate unnecessary code and would not apply to the case.
Using the function empty
we treat at the same time two problems: The case of the person is not logged in, ie the variable $_SESSION['admin']
does not exist; and if the variable has value false
, for in that case empty
returns false
for values of the type false
- and if the user is not admin can not see the page.
I would use the isset
only to treat two different types of cases.
For example : differentiate logged-in 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 stay like this:
if (! isset($_SESSION['admin']) || $_SESSION['admin'] == false) {
// ...
}
See how unnecessary the use of isset
, if we were to replace the first form.
Session PHP. Has on your website ?
– Diego Souza
At first I was using Session, but it was giving some errors, then I changed
– Ricardo Afonso