:o
First of all, my apologies for having two threads... but this was a totally different issue than my other topic.

If a user requests a protected page and is prompted to login (using sessions), how is it possible to allow that login to send him/her right back to the orginal page they wanted after the login?

While searching the forum... I've found the logic is this:

If the login function (on the protected page) can't authenticate the user, it can present a login form
instead of the protected URL, posting back to your login.php with a hidden form
field containing the URL. On successful login, it can issue a "Location" header
back to the URL saved from earlier.

From my readings... I think this can be accomplished somehow using: $_SERVER['HTTP_REFERER']

But I am not clear about where to use that in my code.

The header on the "protected" page that checks to see if user is logged in:

<?php
session_start();
if (!isset($_SESSION['db_is_logged_in']) || $_SESSION['db_is_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}
?> 

and here's the code on the login page... which at the moment CLEARLY defines the browser-out page using a header as "main.php"... I'd like to change this to redirect to whatever the page that was just previously requested (rather than write a million specific login pages):

<?php
// we must never forget to start the session
session_start();

MySQL_connect("localhost", 'username', 'password'); MySQL_select_db("members");


$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {

$userId   = $_POST['txtUserId'];
$password = $_POST['txtPassword'];

// check if the user id and password combination exist in database
$sql = "SELECT user_id
        FROM members
        WHERE user_id = '$userId' AND user_password = PASSWORD('$password')";

$result = mysql_query($sql) or die('Query failed. ' . mysql_error());

if (mysql_num_rows($result) == 1) {
    // the user id and password match,
    // set the session
    $_SESSION['db_is_logged_in'] = true;

    // after login we move to the main page
    header('Location: main.php');
    exit;
} else {
    $errorMessage = 'Sorry, wrong user id / password';
}

}
?> 

Thanks a million...

~Wayne

    $_SERVER['HTTP_REFERER'] isnt a very good way at checking where a user has originated. For all you know they could have come from another site, or even not have the Superglobal set at all.

     if (mysql_num_rows($result) == 1) {
            // the user id and password match,
            // set the session
            $_SESSION['db_is_logged_in'] = true;
    
        // after login we move to the main page
        if (isset($_SERVER['HTTP_REFERER']))
            header("location: ".$_SERVER['HTTP_REFERER']);
        else
            header('Location: main.php');
        exit;
    } else {
        $errorMessage = 'Sorry, wrong user id / password';
    } 
    

    its not a great example but it shows you where it should be added. For a better use you really should have the Login page have returned a value to where they want to go either by Session, GET or other method and have it in a hidden field.

      Thank you... that was quick!

      My idea was to make two login pages... one for folks who want to login by clicking "member login" button on the top of anypage of the site. Those that do this will be redirected to the main "member news" page inside the protected member section.

      My other concern was for those that requested a particular protected page before they logged in, I'd hate to send them to the same "member news" page when they were trying to get somewhere else. If I name this login page something different... and use it as the "default" login page that will come up whenever a protected page is requested... wouldn't that work? In theory, it would always want to send you back to the page you just requested.

      ... I think... I'm gonna go play and see...

      Hmmm... just tried modifying my login page with the above code... now when I enter my username and password it simply shows me the login page again... no session is started.

      ~Wayne

        I think I'm hot on the trail here... just modified the "protected page" to this:

        <?php
        // like i said, we must never forget to start the session
        session_start();
        
        // is the one accessing this page logged in or not?
        if (!isset($_SESSION['db_is_logged_in']) || $_SESSION['db_is_logged_in'] !== true) {
            // not logged in, move to login page
            header('Location: login.php?redir='.$_SERVER['PHP_SELF']);
            exit;
        }
        ?> 
        

        and then the login page to:

        <?php
        // we must never forget to start the session
        session_set_cookie_params (0, '/', '.domain.com');
        
        session_start();
        
        MySQL_connect("localhost", 'username', 'password'); MySQL_select_db("members");
        
        
        $errorMessage = '';
        if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
        
        $userId   = $_POST['txtUserId'];
        $password = $_POST['txtPassword'];
        
        // check if the user id and password combination exist in database
        $sql = "SELECT user_id
                FROM members
                WHERE user_id = '$userId' AND user_password = PASSWORD('$password')";
        
        $result = mysql_query($sql) or die('Query failed. ' . mysql_error());
        
        if (mysql_num_rows($result) == 1) {
            // the user id and password match,
            // set the session
            $_SESSION['db_is_logged_in'] = true;
        
            // after login we move to the main page  
        if ($_GET['redir']) {
        header('Location: '.$_GET['redir']);
            exit;
        } else {
            $errorMessage = 'Sorry, wrong user id / password';
        }
        
        }
        ?>
        
         <html>
        <head>
        <title>Basic Login</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        </head>
        
        <body>
        
        <?php
        if ($errorMessage != '') {
        ?>
        <p align="center"><strong><font color="#990000"><?php echo $errorMessage; ?></font></strong></p>
        <?php
        }
        ?>
        <form method="post" name="frmLogin" id="frmLogin">
        <table width="400" border="1" align="center" cellpadding="2" cellspacing="2">
        <tr>
        <td width="150">User Id</td>
        <td><input name="txtUserId" type="text" id="txtUserId"></td>
        </tr>
        <tr>
        <td width="150">Password</td>
        <td><input name="txtPassword" type="password" id="txtPassword"></td>
        </tr>
        <tr>
        <td width="150">&nbsp;</td>
        <td><input type="submit" name="btnLogin" value="Login"></td>
        </tr>
        </table>
        </form>
        </body>
        </html> 
        

        Not sure what's wrong here... but I'm getting an error message when redirected to the login page:


        Parse error: parse error, unexpected $ in /home/rimea/www/www/login.php on line 76

        Thanks for looking.

        ~Wayne

          That message always or almost always indicates a missing curly brace ( } ) somewhere. Look at the second "if" block in your code.

            😃
            Wonderful! Thank you!!! How does one mark a thread resolved? Is it as simple as going back to the orginal subject and modifying it or am I missing something?

            I placed the ( } ) in the end... and it works! (I assume that's where it technically belonged.)

            <?php
            // we must never forget to start the session
            session_set_cookie_params (0, '/', '.domain.com');
            
            session_start();
            
            MySQL_connect("localhost", 'username', 'password'); MySQL_select_db("members");
            
            
            $errorMessage = '';
            if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
            
            $userId   = $_POST['txtUserId'];
            $password = $_POST['txtPassword'];
            
            // check if the user id and password combination exist in database
            $sql = "SELECT user_id
                    FROM members
                    WHERE user_id = '$userId' AND user_password = PASSWORD('$password')";
            
            $result = mysql_query($sql) or die('Query failed. ' . mysql_error());
            
            if (mysql_num_rows($result) == 1) {
                // the user id and password match,
                // set the session
                $_SESSION['db_is_logged_in'] = true;
            
                // after login we move to the main page  
            if ($_GET['redir']) {
            header('Location: '.$_GET['redir']);
                exit;
            } else {
                $errorMessage = 'Sorry, wrong user id / password';
            }
              }
            }
            ?> 
            

            ~Wayne

              I'm not 100% sure, but I'd say right after the "exit" line:

              // we must never forget to start the session 
              session_set_cookie_params (0, '/', '.rimea.org'); 
              
              session_start(); 
              
              MySQL_connect("localhost", 'username', 'password'); MySQL_select_db("members"); 
              
              
              $errorMessage = ''; 
              if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { 
              
              $userId   = $_POST['txtUserId']; 
              $password = $_POST['txtPassword']; 
              
              // check if the user id and password combination exist in database 
              $sql = "SELECT user_id 
                      FROM members 
                      WHERE user_id = '$userId' AND user_password = PASSWORD('$password')"; 
              
              $result = mysql_query($sql) or die('Query failed. ' . mysql_error()); 
              
              if (mysql_num_rows($result) == 1) { 
                  // the user id and password match, 
                  // set the session 
                  $_SESSION['db_is_logged_in'] = true; 
              
                  // after login we move to the main page   
                  if ($_GET['redir']) { 
                      header('Location: '.$_GET['redir']); 
                      exit; 
                  }
              } else { 
                  $errorMessage = 'Sorry, wrong user id / password'; 
              } 
              }
                Write a Reply...