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:

<?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.


<!--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
	}
?>

    $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
    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: [man]header/man ). 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,

      Would it be easier to do the following:
      Add this code above the first if statement on the "log In" page:

      <?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:

      <?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:

      if($username == TRUE){
      	$UserName = $username['USER_NAME'];
      	$Password = $username['USER_PASSWORD'];
      	$_SESSION['ValidLogIn'] = $UserName;
      	include 'index.php';
      }
        hugoriffic;11025723 wrote:

        Would it be easier to do the following:
        Add this code above the first if statement on the "log In" page:

        <?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:

        <?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:

        /page.php

        ... and that's assuming there's no query string.

        So, you could ltrim the "/" off of it, or handle is this way:

        header("Location: http://mysite.com".$url);

        If so, then how would I change this 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:

        	$UserName = $username['USER_NAME'];

        to something similar to this:

        	$_SESSION['UserName'] = $username['USER_NAME'];

        so the username will continue to be available on your other pages.

        Hope this is helpful. 🙂

          dalecosp,
          Are you saying the

          header("Location: http://mysite.com".$url");

          should be moved here

          if($username == TRUE){
          $_SESSION['UserName'] = $username['USER_NAME']; 
          header("Location: http://mysite.com".$url");
          exit();	
          }

            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?

              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:

              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.

                dalecosp;11025765 wrote:

                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.

                  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"?

                    Looks like I had a typo in there before:

                    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:

                    echo "http://www.itweb.mysite.com".$url;
                    exit;

                    and then delete those lines for production, replacing them with the [man]header/man call.

                      ... or just leave the header() call in place exactly as is and simply view the response headers the server sent to your web browser. 😉

                        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:

                        if (!isset($_SESSION['ValidLogIn'])){
                        

                        This now sits underneath the code (with the valid urls):

                        <?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:

                        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.

                          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??

                            hugoriffic;11025811 wrote:

                            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?

                            hugoriffic;11025811 wrote:

                            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.

                            hugoriffic;11025811 wrote:

                            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).

                            hugoriffic;11025907 wrote:

                            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.

                              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

                              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

                              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

                              <?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

                              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

                              if (!isset($_SESSION['ValidLogIn'])){
                              

                              does nothing because there is no ValidLogIn session ID being set so this needs to be removed.
                              Because these lines

                              $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

                              if (isset($_SESSION['ValidLogIn'])){
                              

                              needs to be changed to

                              if (isset($_SESSION['UserName])){
                              

                              Is this correct??

                                hugoriffic;11025915 wrote:

                                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

                                session_start();
                                

                                Then you should read someone else's code. If you do not call session_start() on a "log in page", you cannot assign any value to the $_SESSION array, like a username, user ID, "is_logged_in" flag, etc. There is, I suppose, some room for ambiguity here; for example, what's a "log in page", exactly? Is it the form for entering user credentials, or the handler that processes said credentials once they're submitted?

                                  It is the form for entering credentials. OK, other than that, does is my logic correct? Am I stepping through the processes properly?

                                    I meant to ask if my logic is correct? Does it look good?

                                      Please, can someone comment on my logic??

                                        5 days later
                                        Write a Reply...