Submitting a user to a link page

I am trying to set up a redirect after a successful user registration.

The login page should redirect the user to the page to which they were denied access after they successfully logged in.

For example, if a user clicks on "My Account" before logging in (without a session), they are redirected to the login page, but as soon as they log in, how to send them to the "My Account" page

Methods used include $_SESSION['HTTP_REFERER] .

Any help would be greatly appreciated.

+6
source share
5 answers

Using $_SERVER['HTTP_REFERER'] is dangerous because the referrer will be the same login page if the user received an error while trying to login (for example, as an incorrect password). You must save the return URL inside the session variable before redirecting the user to the login page, and then after successful login, redirect them to the saved return URL.

For example, let's say you need to protect page.php , you could have something like this at the beginning of the file:

 if (empty($_SESSION['user'])) { $_SESSION['backURL'] = $_SERVER['REQUEST_URI']; header('Location: login.php'); exit; } 

Then, after the user successfully logs in, you can fill in the variable $_SESSION['user'] , and then redirect to the URL that you saved before sending it to the login page (or to the root of the site, if this is so, t have any return url stored for any reason):

 $backURL = empty($_SESSION['backURL']) ? '/' : $_SESSION['backURL']; unset($_SESSION['backURL']); header('Location: ' . $backURL); exit; 
+8
source

Try the following:

 <?php header("Location: " . $_SERVER["HTTP_REFERER"]); ?> 
+1
source

Enter the page where the session variable set is redirected, which is the URL of this page:

 session_start(); if (!$logged_id) { $_SESSION['redirect_url'] = $_SERVER['PHP_SELF']; header('Location: login.php'); exit; } 

Then after successful login redirect them to this URL:

 session_start(); /* Login code goes here */ $redirect_url = (isset($_SESSION['redirect_url'])) ? $_SESSION['redirect_url'] : '/'; unset($_SESSION['redirect_url']); header("Location: $redirect_url", true. 303); exit; 
+1
source
 header("Location: " . $_SERVER["HTTP_REFERER"]); 

Let's do it, but note:

You CANNOT output ( echo , print_r , ect ect) anything before sending custom headers.

0
source

You should remember the last page visited in a variable like $_SESSION["last_page"] (exclude the login page). After the user has successfully logged in, enter the value of the variable and redirect the user to his previous location.

You cannot use referrer. For example, if a user does not complete his first login attempt, in the second attempt his referent will become a login page.

Another way is to authenticate the user using ajax without a separate login page. If the login was successful, you can simply refresh the page using javascript.

0
source

Source: https://habr.com/ru/post/913872/


All Articles