简体   繁体   中英

how to redirect the user back to desired URL after login page in PHP?

OK. I have a page called plans.php, inside I have three links (Plan 1, Plan 2, Plan 3). Each link has its own page and it redirects to login page (login.php, which works fine). So if the user is not logged in when they click lets say on "Plan 2" it will force the user to login so they can see the desired page, all depends of what "Plan" the user chooses.

PROBLEM: I'm having a hard time redirecting the user back to the "desired Plan (URL)".

Solution: If the user chooses "Plan 1 or Plan 2 (whatever plan)" then it will force user to login (I have that working fine), after user logs in successfully the user has to be redirected to their respective "Plan page".

If any is familiar with this issue please help.

plans.php

<a href="plan-1.php">Plan 1</a>
<a href="plan-2.php">Plan 2</a>
<a href="plan-3.php">Plan 3</a> 

plan-2.php

<?php
 ob_start();
   include "header.php";

   if(!$current_user) { 
     require_login();
    }
 ob_end_flush();
?>

HTML code: What the user is going to see after login page.

<p>Hello, you have been redirected to "Plan 2"</p>

login.php

<?php 
  ob_start();
    include "header.php";
    if($current_user) { 
       req_logout(); }
  ob_end_flush();
?>

HTML code:

 <form action="authenticate.php" method="POST">
  <label for="email">Email</label><br/>
  <input type"text" class="input" name="username" id="username" />
  <label for="password">Password</label><br/>
  <input name="password" type="password" class="input" id="password"/>
  <input type="submit" value="Sign In" class="submit"/>
 </form>

This file verifies user credentials where the login form submits to.

authenticate.php

<?php
  session_start();
  require_once "db.php";
  db_connect();
  require_once "auth.php";

  $user_id = credentials_valid($_POST['username'], $_POST['password']); 
     if($user_id){
      log_in($user_id);

    if($_SESSION['redirect_to']){
          header("Location: " . $_SESSION['redirect_to']);
          unset($_SESSION['redirect_to']);

        }else{
         // Default page after user logs in.
          header("Location: manage.php");
    }
    }else{
       header("Location: login.php?error=1");
       exit("You are being redirected");
    }
?>

I have some PHP functions in this file.

auth.php

// Logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}


// Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user){
    if($_SESSION['user_id']){
        $user_id = intval($_SESSION['user_id']);
        $query = "SELECT *
                  FROM `********`
                  WHERE `id` = $user_id";

        $result = mysql_query($query);
        if(mysql_num_rows($result)){
            $current_user = mysql_fetch_assoc($result);
            return $current_user;
        }
    }
}
 return $current_user;   
}

// Requires a current user (Restrict Access to Page)
function require_login(){
if(!$current_user){
       $_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
        header('Location: signin.php');
    exit("You must log in.");
}
}

Try to send a parameter when a user clicks on a plan link. Pass or save the parameter and after successful login, use that parameter to redirect to the proper page.

in plan-2.php

session_start();
$_SESSION['redirect_to']="plan-2.php";

EDIT: Here is complete solution using parameter sending via GET and POST (as I have been asked for):

plans.php

<a href="plan.php?no=3">Plan 1</a>
<a href="plan.php?no=3">Plan 2</a>
<a href="plan.php?no=3">Plan 3</a> 

plan.php

<?php
 ob_start();
   $getbackURLid=$_GET['no'];
   include "header.php";

   if(!$current_user) { 
     require_login($getbackURLid);
    }
 ob_end_flush();
?>

signin.php

<?php 
  ob_start();
    include "header.php";
    if($current_user) { 
       req_logout(); }
  ob_end_flush();
?>

HTML code:

 <form action="authenticate.php" method="POST">
  <label for="email">Email</label><br/>
  <input type"text" class="input" name="username" id="username" />
  <label for="password">Password</label><br/>
  <input name="password" type="password" class="input" id="password"/>
  <input type"hidden" name="url" value="<?php echo $_GET['url'];?>" />
  <input type="submit" value="Sign In" class="submit"/>
 </form>

authenticate.php

<?php
  session_start();
  require_once "db.php";
  db_connect();
  require_once "auth.php";

  $user_id = credentials_valid($_POST['username'], $_POST['password']); 
     if($user_id){
      log_in($user_id);

    if($_POST['url']){
          header("Location: plan.php?no=".$_POST['url']);
          unset($_SESSION['redirect_to']);

        }else{
         // Default page after user logs in.
          header("Location: manage.php");
    }
    }else{
       header("Location: login.php?error=1");
       exit("You are being redirected");
    }
?>

auth.php

// Logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}


// Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user){
    if($_SESSION['user_id']){
        $user_id = intval($_SESSION['user_id']);
        $query = "SELECT *
                  FROM `********`
                  WHERE `id` = $user_id";

        $result = mysql_query($query);
        if(mysql_num_rows($result)){
            $current_user = mysql_fetch_assoc($result);
            return $current_user;
        }
    }
}
 return $current_user;   
}

// Requires a current user (Restrict Access to Page)
function require_login($getbackURLid){
if(!$current_user){
       $_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
        header('Location: signin.php?url=$getbackURLid');
    exit("You must log in.");
}
}

Since some popular browsers (like Chrome) cache server redirect responses, if you do a server redirect, the requested page will always redirect to the same page as the first redirect the browser encountered.

To solve this, you validation PHP page should contains the following redirection:

<?php

    function curPageURL() {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    // Check if the session's user is logged in properly
    $redirect = "";
    if (!$_SESSION['current_user']) {
        $target_page= "http://www.myserver.com/login?sender=" + urlencode(curPageURL());

        echo "<html>";
        echo "  <head>";
        echo "    <script>";
        echo "      window.location = '", $target_page, "';";
        echo "    </script>";
        echo "  </head>";
        echo "  <body></body>";
        echo "</html>"
    } else {
?>

<html>
  <head>
  </head>
  <body>
    <!-- put your page html here -->
  </body>
</html>

<?php
    }
?>

Please note that I'm not a PHP developper, my code may contains syntax errors and must be revised properly.

So... yeah, the code may look a little bit crappy but the important thing to remember is to not use the http response redirection. I tried all possible ways to disable response caching but chrome don't care at all. The only safe way I found is to do the redirection using javascript. I did not try the META http-equiv="refresh" way though. I guess it's safe as well since we see that often.

Another thing to remember is to avoid rendering your sensitive page content if the user is not logged in.

With that in mind, you should be good to go.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM