How to redirect back after login in PHP
Sometime we get link from a site, when we click the invitation link, it just send us to the index page for login(as we are not logged in in th开发者_开发技巧at site), when the login finishes, the site just redirect us to the link on which we clicked.
How this can be achieved in php?
Let's say the "destination page" as called "a.php
" ; here's a possible way of doing what you're describing :
- You first call
a.php
from your browsera.php
detects you are not logged in- it redirects you to
index.php
, with a parameter in the URL tellingindex.php
you should be redirected toa.php
when logged-in - the redirection is done using the
header
function, with aLocation
header that points to something likehttp://yoursite.com/index.php?destination=a.php
- On
index.php
, you deal with the logging-in mecanism- i.e. a form, with a hidden field, in which the
$_GET['destination']
is stored (properly escaped, of course) - That form posts to either
index.php
(i.e. itself) or another page ; doesn't quite matter.
- i.e. a form, with a hidden field, in which the
- When the logging-in form is posted :
- you check the credentials
- if login+password are OK :
- if there is a
destination
field in the form's data, you redirect the user to the corresponding page - else, you redirect the user to a default page.
- Of course, it might be interesting to check the content of the
destination
field, to make sure you are only accepting redirection to a "valid" page (the definition of "valid" can change -- but can at least mean "a page on your site")
- if there is a
You might also want to try...
start_session();
$_SESSION[destination] = strip_tags($_GET[destination]);
..as opposed to calling the variable as a hidden field. Then do your check-downs from there on the POST (what check functions you need) e.g.
if ($_SESSION[destination] !='' || empty($_SESSION[destination]) && !is_numeric($_SESSION[destination])){
header('Location:'.$_SESSION[destination]);
}
精彩评论