This code will not work if you have already logged in and filled in these values in the session. The session exists on the server, regardless of what you do in the browser, and only dies after certain time without user activity or when it is explicitly cleared.
If you want the person not to be able to access by pasting a link, you need to do the following sequence of steps:
- Generate a session value (with a name different from those that store a user name and access level, in your case) on any other page. Name it as an access token or something;
- On the admin page, see if that value in the specific session is filled in. If you are, allow access, otherwise redirect to another page;
- Finally, still on the admin page, after the above check, delete the value. This causes the next access to the admin page to be redirected. Now you will only be able to access the admin page after accessing the token generator page again.
Editing to add code
On any page, other than the panel, add the following logic:
$_SESSION['autorizacaoPainel'] = true;
On the panel page, add the following logic:
if ($_SESSION['autorizacaoPainel']) {
unset($_SESSION['autorizacaoPainel']);
} else {
header("Location: login.php");
}
So you will always need to access the page you fill 'autorizacaoPainel'
before any access to the panel.
If you copy and paste in the same browser, with the same cookies, you will have access. Second it is better to use
!isset(...)
than== ""
, avoids "Undefined variable" errors. If you allow the session to be passed by URL parameter you can copy the session identifier present in the URL, turn it off usingsession.use_trans_sid
for0
and thesession.use_only_cookies
for1
.– Inkeliz
Pedro, there’s a detail you wanted to know before you asked your question: when you say you copy and paste the link and can access it, are you doing it in another browser? If you are doing it in the same browser, it is normal for the session to remain active. Try to access by copying and pasting the link through another page.
– FabianoLothor
Put that code before yours
IF
to see why your code is going wrong:var_dump($_SESSION['usuarioNome'], $_SESSION['usuarioNivelAcesso'])
– FabianoLothor
Fabiano, I’m doing in the same browser, I’ll do what you said now
– Pedro Ribeiro
Fabiano, gave it here in var_dump: C: wamp64 www painel_prefeitura segurnca.php:3:string 'Pedro Henrique Fonseca Ribeiro' (length=30) C: wamp64 www painel_prefeitura segurnca.php:3:string '1' (length=1)
– Pedro Ribeiro
@Pedroribeiro this then answers your question, after all, as you can see in var_dump(), the variables are not empty as you expected.
– FabianoLothor