Redirect user to previous page after valid log in
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: Redirect user to previous page after valid log in

  1. #1
    Junior Member
    Join Date
    Mar 2013
    Posts
    11

    Redirect user to previous page after valid log in

    I'm having trouble figuring out how to direct a user back to the page he/she was on before they decided to log in. I've looked at both the $_SERVER['REQUEST_URI'] and the $_SERVER['HTTP_REFERRER'] methods but the code examples I have seen do not match my code so it is hard to understand how to use these. I also want, once a valid log in has occurred, to change the "Log In" and "Create Account" links to "Log Out" and "Edit Profile". Plus add a greeting to welcome the user.
    I know this has everything to do with the session variable but how to set it up and get it to do these things baffles me. Any help would be greatly appreciated.
    Oh, one last thing. My showForm() messages do not work properly. It either states "Welcome" or "Username and Password Do Not Match" are my if statements correct??

    Here is the code for my log in page:
    Code:
    <?php
    session_start();
    
    if (!isset($_SESSION['ValidLogIn'])){
    
    //if username and password are empty display welcome message
    if(empty($_POST['txtUserName']) &&  empty($_POST['txtPassword'])) 
    		{
    			showForm('Welcome!');
            	exit();
    		}
    
    //validate text was entered in UserName text box
    if(empty($_POST['txtUserName']) && isset($_POST['btnSubmit']))
            {
               showForm('Please Enter A User Name');
               exit();
            }
       else
    		{
               $UserName = $_POST['txtUserName'];
            }
    
    //validate text was entered in password text box
    if(empty($_POST['txtPassword']) && isset($_POST['btnSubmit']))
           {
               showForm('Please Enter A Valid Password');
               exit();
           }
       else
           {
               $Password = $_POST['txtPassword'];
           }
    
    $UserName = $_POST['txtUserName'];
    $Password = $_POST['txtPassword'];
    
    //validate username and password match
    if($Password != Password($UserName) && isset($_POST['btnSubmit']))
           {
               showForm('User Name And Password Do Not Match!');
               exit();
           }
           }
    function Password($UserName)
    {
       //database login
       $dsn = 'mysql:host=XXX;dbname=XXX';
       $username='XXX';
       $password='XXX';
       //variable for errors
       $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
       //try to run code
       try {
       //object to open database
       $db = new PDO($dsn,$username,$password, $options);
       //check username against password
           $SQL = $db->prepare('SELECT * FROM user WHERE USER_NAME = :UserName and USER_PASSWORD = :Password');
    	   $SQL->bindValue(':UserName', $UserName);
    	   $SQL->bindValue(':Password', $Password);
    	   $SQL->execute();
    	   $username = $SQL->fetch();
    			
    			if($username == FALSE)
    			{
    				$Password = null;
    				showForm('Invalid log in information.');
    				exit();
    			}
    			if($username == TRUE){
    				$UserName = $username['USER_NAME'];
    				$Password = $username['USER_PASSWORD'];
    				$_SESSION['ValidLogIn'] = $UserName;
    				include 'index.php';
    				}
             
           return $password;
           $SQL->closeCursor();
           $db = null;
                 
           } catch(PDOException $e){
               $error_message = $e->getMessage();
               echo("<p>Database Error: $error_message</p>");
               exit();
           }
           
    }
    function showForm($formMessage = "Welcome!")
    {?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Log In</title>
    <link rel="stylesheet" href="styles/default-styles.css" type="text/css" />
    <link rel="stylesheet" href="styles/FormStyle.css" type="text/css" />
    <script type="text/javascript" src="js/validateLogInForm.js/validateLogInForm.js"></script>
    </head>
    
    <body id="logPage">
       <div id="wrapper">
           
           <?php include('includes/header.php'); ?>
           <?php include('includes/topNavigation.php'); ?>
         
           <div id="mainContent">
               <div class="formDiv">
                   <form name="registerForm" id="registerForm" action="" method="post">
                    <?php if ($formMessage !="") echo "<h2 style=\"color:#FF0000; text-align: center\">".$formMessage."</h2>"; ?>
                       <h1 style="color:#FF530D; text-align: center">Log into your account here!</h1>
                 
                       <fieldset id="security">
                           <legend>Security</legend>
                           <label for="txtUserName" class="boxLabel">User Name:</label>
                           <input type="text" id="txtUserName" name="txtUserName" autofocus="autofocus" required="required" />
                           <script type="text/javascript">
                               if(!("autofocus" in document.createElement("input")))
                               {
                                   setTimeout(function(){
                                       document.getElementById("txtUserName").focus();
                                   }, 10);
                                 
                               }
                               </script>
                           <label for="txtPassword" class="boxLabel">Password:</label>
                           <input type="password" id="txtPassword" name="txtPassword" required="required" />
                       </fieldset>
                     
                       <fieldset id="submission">
                           <div id="buttons">
                               <input type="submit" id="btnSubmit" name="btnSubmit" value="Submit" onclick="return validateLogInForm()"/>
                               <input type="reset" id="btnReset" name="btnReset" >
                           </div><!--end buttons-->
                       </fieldset>
    </p>
                   </form>
               </div><!--end div class=formDiv-->
           </div><!--end div id=mainContent-->
                   
           <?php include('includes/footer.php'); ?>
                 
       </div><!--end div id=wrapper-->
    </body>
    </html>
    <?php
    }
    ?>
    And here is the code where I want to place the changes to the "Log In" links etc.
    Code:
    <!--Check to see if user is logged in. If session does not exist, serve header without personal greeting. If session does exist, serve second header-->
    <?php
    session_start();
    
    if (isset($_SESSION['ValidLogIn'])){
    	//add code to get user name and change link messages
    }
    	else {?>
    	<div id="header">
    		<div id="headerTop">
    			<div id="greeting">
    	            		
    			</div><!--end div id=greeting-->
    			<ul id="logIn">
    				<li><a href="logIn.php">Log-In</a></li>
    				<li><a href="registerResponse.php">Register</a></li>
    			</ul>
    		</div><!--end div id=headerTop-->
    		
    		<div id="headerBottom">
    			<div id="logo">
    		            	
    			</div><!--end div id=logo--> 
    			<div id="keyboard">
    				
    			</div><!--end div id="keyboard"-->
    		</div><!--end div id=headerBottom-->          
    	</div><!--end div id=header-->
    <?php
    	}
    ?>

  2. #2
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,723
    $_SESSION is an array that PHP stores for you, associated with a particular client/user/browser. It "tags" the client/user/browser with a cookie that you don't have to worry about, and keeps the data in a file on the server (as opposed to $_COOKIE storage, where you can store data on the client computer).

    So, since session is an array, you can stick whatever you want in there. For example, to "fix" your first problem, you might call session_start() on the beginning of every page of your site, and record the current page name similar to this:
    PHP Code:
    <?php
    session_start
    (); // get our session array working

    $pagedata pathinfo($_SERVER['REQUEST_URI']); //pathinfo() is a cool function that parses REQUEST_URI for us!

    $_SESSION['last_page_visited'] = $pagedata['basename']; // basename is part of the output of the pathinfo() call above.
    So now you know where they were. The next step would be to redirect them, after a successful login, back to that page (hint: header() ). Be careful that when you do the login page, you don't overwrite $_SESSION['last_page_visited'] or you'll just end up redirecting back to the login page!

    HTH,
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  3. #3
    Junior Member
    Join Date
    Mar 2013
    Posts
    11
    Would it be easier to do the following:
    Add this code above the first if statement on the "log In" page:
    Code:
    <?php
    if(isset($_SESSION['url'])) {
       $url = $_SESSION['url'];
    }
    else {
       $url = "index.php";
    }
    header("Location: http://mysite.com/$url");
    and where the first "url" is listed put in the previous page visited and in the second put in login.php.

    And then at the top of every other page put:
    Code:
    <?php
    session_start(); 
    $_SESSION['url'] = $_SERVER['REQUEST_URI'];
    and where the "url" is here put the current page they are on there.

    If so, then how would I change this code:
    Code:
    if($username == TRUE){
    	$UserName = $username['USER_NAME'];
    	$Password = $username['USER_PASSWORD'];
    	$_SESSION['ValidLogIn'] = $UserName;
    	include 'index.php';
    }

  4. #4
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,723
    Quote Originally Posted by hugoriffic View Post
    Would it be easier to do the following:
    Add this code above the first if statement on the "log In" page:
    Code:
    <?php
    if(isset($_SESSION['url'])) {
       $url = $_SESSION['url'];
    }
    else {
       $url = "index.php";
    }
    header("Location: http://mysite.com/$url");
    and where the first "url" is listed put in the previous page visited and in the second put in login.php.
    Well, header() is going to redirect them as soon as it's called ... don't you want to check their credentials first?

    And then at the top of every other page put:
    Code:
    <?php
    session_start(); 
    $_SESSION['url'] = $_SERVER['REQUEST_URI'];
    and where the "url" is here put the current page they are on there.
    Well, that will work ... more or less. REQUEST_URI actually gives a string like this:
    Code:
    /page.php
    ... and that's assuming there's no query string.

    So, you could ltrim the "/" off of it, or handle is this way:
    PHP Code:
    header("Location: http://mysite.com".$url); 
    If so, then how would I change this code:
    Code:
    if($username == TRUE){
    	$UserName = $username['USER_NAME'];
    	$Password = $username['USER_PASSWORD'];
    	$_SESSION['ValidLogIn'] = $UserName;
    	include 'index.php';
    }
    I'm not sure off the top of my head (and have work to do here). But wouldn't *that* be the place for the header call? If it was set, of course. They've just successfully logged in at that point, you've set the session var ... so if you have a redirect URL at that point, send 'em back where they came from. You probably would want to change this:
    PHP Code:
        $UserName $username['USER_NAME']; 
    to something similar to this:
    PHP Code:
        $_SESSION['UserName'] = $username['USER_NAME']; 
    so the username will continue to be available on your other pages.

    Hope this is helpful.
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  5. #5
    Junior Member
    Join Date
    Mar 2013
    Posts
    11
    dalecosp,
    Are you saying the
    Code:
    header("Location: http://mysite.com".$url");
    should be moved here
    Code:
    if($username == TRUE){
    $_SESSION['UserName'] = $username['USER_NAME']; 
    header("Location: http://mysite.com".$url");
    exit();	
    }

  6. #6
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,723
    Does that accomplish your purpose? If so, yes. As I read it, (note that I only briefly glanced at your project-in-the-making), you want to redirect the user to the resource he/she was looking at before they visited the log-in page. But, I assume you want to go ahead and log them in first (after all, that was why they left the referring URL and came to the login page, right?) ... so in that case it would make sense to move the redirection (header() call) until the login had been accomplished ... right?
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  7. #7
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    13,974
    I prefer to avoid redirects entirely, and simply include/call a user authorization function/class at the top of each controlled page. That function basically does:
    Code:
    if(login request received)
       if(login correct)
          return // requested page will now display
       else
          display the login form (with action="") with error message
          exit // prevent rest of page from displaying
       endif
    elseif(user is already logged in)
       return // requested page will now display
    else
       display the login form (with action="")
       exit // prevent rest of page from displaying
    endif
    Then each controlled page just needs to call that function at the top.
    Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett

    "But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because he’s a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html


    eBookworm.us

  8. #8
    Junior Member
    Join Date
    Mar 2013
    Posts
    11
    Quote Originally Posted by dalecosp View Post
    Does that accomplish your purpose? If so, yes. As I read it, (note that I only briefly glanced at your project-in-the-making), you want to redirect the user to the resource he/she was looking at before they visited the log-in page. But, I assume you want to go ahead and log them in first (after all, that was why they left the referring URL and came to the login page, right?) ... so in that case it would make sense to move the redirection (header() call) until the login had been accomplished ... right?
    Yes, I want to redirect the user back to the previous page they were on before they logged in. And yes, only if there is a valid log in do I want to redirect them. I cannot express to you how grateful I am for your help, especially if this works. I have been muddling through this for over a week trying all kinds of different methods to get the redirect to work. I'm going to try it later tonight and let you know how it goes.

  9. #9
    Junior Member
    Join Date
    Mar 2013
    Posts
    11
    One more thing: since the REQUEST_URI only returns something along the lines of "/page.php" then where I put the url would I need to code it like this: "http://www.itweb.mysite.com"?

  10. #10
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,723
    Looks like I had a typo in there before:

    PHP Code:
    header("Location: http://www.itweb.mysite.com".$url); 
    That sort of thing should work. To debug stuff like this, in a development environment, just do something like:

    PHP Code:
    echo "http://www.itweb.mysite.com".$url;
    exit; 
    and then delete those lines for production, replacing them with the header() call.
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  11. #11
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,432
    ... or just leave the header() call in place exactly as is and simply view the response headers the server sent to your web browser.

  12. #12
    Junior Member
    Join Date
    Mar 2013
    Posts
    11
    Everything appears to be working fine. At least it redirects me to the previous page I viewed when I test it. But, from my original post I have the following code near the top of my page on the log in:
    Code:
    if (!isset($_SESSION['ValidLogIn'])){
    This now sits underneath the code (with the valid urls):
    Code:
    <?php
    session_start();
    
    if(isset($_SESSION['url'])) {
       $url = $_SESSION['url'];
    }
    else {
       $url = "index.php";
    }
    But I am not setting the session variable for ValidLogIn anywhere. Therefore, the code on my header page, where I want to change the "Log In" and "Create Account" links to "Log Out" and "Edit Account", plus add a personalized greeting using the members name obviously will not work. Will it?? Since I changed the code to validate a user log in to this:
    Code:
    if($username == TRUE){
    $_SESSION['UserName'] = $username['USER_NAME']; 
    header("Location: http://mysite.com".$url");
    exit();	
    }
    Should I change the name ValidLogIn to UserName?? Or do I need to create a session variable named ValidLogIn within the if statement where I check to see if it is set?
    As a newbie I am unfamiliar with whether or not you can have two session variables running at the same time. What is confusing me is that the header.php page contains only the header information for every page. And for every page I include the header.php. That is where I am getting confused now. Any help would be greatly appreciated on how to solve this.

    I hope this post makes sense. If not, please ask for clarification.

  13. #13
    Junior Member
    Join Date
    Mar 2013
    Posts
    11
    Has anyone had a look at this thread in the past few days? I'm still confused about the if statement with ValidLogIn and whether or not that is necessary or if I should rename it to UserName to get it to work. If need be I can post the entire code as I have it now for clarification as to how it is set up and as to what exactly I am asking here. I'm out of town and do not have access to check the code until I return home on Wednesday.
    I'd truly appreciate any, and all, help I can get in this matter as it is rather confusing to me. I have been researching on the internet and from what i understand you can only have one session variable set up per website. Is this correct??

  14. #14
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,432
    Quote Originally Posted by hugoriffic View Post
    But I am not setting the session variable for ValidLogIn anywhere.
    Then why are you trying to check if it exists before executing some code? Doesn't it seem a bit silly to you to wrap code inside a conditional statement that should never evaluate to anything but false?

    Quote Originally Posted by hugoriffic View Post
    Should I change the name ValidLogIn to UserName?? Or do I need to create a session variable named ValidLogIn within the if statement where I check to see if it is set?
    You can do either one, or you could even pick an entirely different name. What you shouldn't, do, is define something called "foo" in one spot and then check to see if it exists as "bar" in another.

    Quote Originally Posted by hugoriffic View Post
    As a newbie I am unfamiliar with whether or not you can have two session variables running at the same time.
    Not sure what you mean by "running" there. Variables don't "run" at all - they're just pieces of information that are stored somewhere and given a specific name. As for session variables, the default behavior is to store the entire session data in a single file on disk. That one file can have any number of session variables inside of it.

    EDIT: Just to clarify... the "single file on disk" refers to what is done for each session. If 10 users visit your site, there should be 10 different sessions being created and stored on disk (e.g. in 10 different files).

    Quote Originally Posted by hugoriffic View Post
    I have been researching on the internet and from what i understand you can only have one session variable set up per website. Is this correct??
    Most certainly not.
    Last edited by bradgrafelman; 04-01-2013 at 02:59 PM.

  15. #15
    Junior Member
    Join Date
    Mar 2013
    Posts
    11
    OK, I've thought about your reply bradgrafelman, and re-read this entire post from start to finish several times, and now I want to run the logic by everyone to see if I understand it correctly. That way I might be able to figure this out on my own. So, here goes...
    First off every time I have seen a log in page that redirects back to a prior page that log in page did not contain the opening
    Code:
    session_start();
    Only the pages that were linked to it contained this. So, I'm assuming this is unnecessary on the log in page.
    Secondly these lines
    Code:
    if($username == TRUE){
    $_SESSION['UserName'] = $username['USER_NAME']; 
    header("Location: http://mysite.com".$url");
    exit();	
    }
    First check to see if a valid log in has been entered, and if so, the username variable is set to the session ID variable and then the page is redirected back to the previous page.
    The lines that sit on the top of every page including the log in
    Code:
    <?php
    session_start();
    
    if(isset($_SESSION['url'])) {
       $url = $_SESSION['url'];
    }
    else {
       $url = "index.php";
    }
    Start the session ID that has been created from the valid log in then check as to whether the current url matches the url that the user is on and, if so redirects them back to the previous page, or, if not, send them to the index.php page. This only happens if a valid log in was created. Other wise this line occurs
    Code:
    if($username == FALSE)
    {
    	$Password = null;
    	showForm('Invalid log in information.');
    	exit();
    }
    Which keeps them on the log in page and send up the error message.
    Therefore, the line
    Code:
    if (!isset($_SESSION['ValidLogIn'])){
    does nothing because there is no ValidLogIn session ID being set so this needs to be removed.
    Because these lines
    Code:
    $UserName = $_POST['txtUserName'];
    $Password = $_POST['txtPassword'];
    
    //validate username and password match
    if($Password != Password($UserName) && isset($_POST['btnSubmit']))
           {
               showForm('User Name And Password Do Not Match!');
               exit();
           }
    check to see if a valid check in is made pass the variable $UserName down to the valid check which if true sets the session ID.
    Therefore, I should change this line on the header page (where I want to change the log in to log out etc
    Code:
    if (isset($_SESSION['ValidLogIn'])){
    needs to be changed to
    Code:
    if (isset($_SESSION['UserName])){
    Is this correct??

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •