How do I redirect the user to the page they were browsing after the user logged in? I've seen solutions using $ _SERVER ['HTTP_REFERER'] ;, but I do not think that's a good idea, could you help me with some code example?
Thankful
How do I redirect the user to the page they were browsing after the user logged in? I've seen solutions using $ _SERVER ['HTTP_REFERER'] ;, but I do not think that's a good idea, could you help me with some code example?
Thankful
Implement URL storage in your process. Example:
With $_SERVER['HTTP_REFERER']
, you will get the referrer
that was set by the header sent, this is not reliable, but you can reasonably believe in it for this purpose. You can also use a parameter in the URL to indicate which page is approaching.
One method used for both cases is to use ?pagina=
, for example Twitter, Instagram, Facebook:
twitter.com/login?redirect_after_login=%2FInkeliz
instagram.com/accounts/login/?next=%2FInkeliz
facebook.com/login/?next=https%3A%2F%2Fwww.facebook.com%2FInkeliz
This indicates that after login it will go where the parameter indicates.
This way you can have a butt, <div class="fazerLogin">LOGIN</div>
and use it to always add the parameter, for example:
$('.fazerLogin').attr('href',
'https://exemplo.com/login?next=' + encodeURIComponent($(location).attr('href'))
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><aclass="fazerLogin" href="https://exemplo.com/login">LOGIN</a>
Move the mouse to the "LOGIN" to see the new URL path.
Then in PHP do the following:
Get the parameter next
.
Verify next
is valid, matches your domain.
Redirect the user.
For example:
// Define um URL padrão se não houver um válido
function linkEncaminhar($nomeParametro){
$url = 'https://exemplo.com/perfil';
if(isLinkValido($nomeParametro) === true){
$url = urldecode($_GET[$nomeParametro]);
}
return $url;
}
// Verifica se o URL é válido
function isLinkValido($nomeParametro){
$meuDominio = 'https://exemplo.com/';
return isset($_GET[$nomeParametro]) &&
is_string($_GET[$nomeParametro]) &&
substr( urldecode($_GET[$nomeParametro]) , 0, strlen($meuDominio)) === $meuDominio;
}
This way:
$urlRedicionar = linkEncaminhar('next');
header('Location: ' . $urlRedicionar);
That way if https://exemplo.com/login?next=https%3A%2F%2Fexemplo.com%2Fsobre-nos
is accessed after login it will go to https://exemplo.com/sobre-nos
.
/! \ CAUTION:
If there is a link of type
https://exemplo.com/configuracao?excluir_conta=true
without any kind of CSRF-Token , a person can make ahttps://exemplo.com/login?next=https://exemplo.com/configuracao?excluir_conta=true
, hence after the person connects and will be redirected to such a URL, which will do delete the account, in this hypothetical situation!
There is such a problem on a well-known state site ...
You can use header('location:pagina.ext');