Redirect to last page after login

I have a page that lists data, but I do not want to show my telephone numbers unless the user is logged in.

I am using a session variable to check if they are logged in. If they are not a link appears saying please login and they go to the login page.

But my problem is they then have to go back and search for the listing and look for it again.

Is there a way I can redirect them back to the page they came from?
Header.php ------
<?php session_start(); 
session_register("sessFirstName");
$sessFirstName = $HTTP_POST_VARS['username'];
?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}
 
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}
 
if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['logged'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['logged']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "index.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
 
Results Page: ----
<?php if ($_SESSION['logged'] == "true") { echo ('<table border="0">
                                <tr>
                                  <td valign="top" class="JobText">Contact: '.$row_job_results["rest_contact"].'  </td>
                                  <td valign="top" class="JobText">Contact Number: '.$row_job_results["rest_conttel"].' </td>
                                </tr>
       </table>');} else echo ('<table border="0">
                                <tr>
                                  <td valign="top" class="JobText"><a href="login.php">Login to see this</a></td>
                                  <td valign="top" class="JobText"><a href="login.php">Login to see this</a></td>
                                </tr>
       </table>');?>

Open in new window

LVL 4
cataleptic_stateAsked:
Who is Participating?
 
cataleptic_stateConnect With a Mentor Author Commented:
So I add the:
if(isset($_GET['redirect'])){
        header("Location: " . $_GET['redirect'] );
} else {
        header("Location: " . $MM_redirectLoginSuccess );
}

to login.php?
0
 
wellsoCommented:
Maybe echo this little bit of JavaScript?
<script type="text/javascript">
history.go(-1)
</script>

Open in new window

0
 
wellsoCommented:
or potentially you could stored the referring page maybe $_SERVER['PHP_SELF'] in a session variable and then use header() to redirect back to it
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
markloganCommented:
Change the HTML for the login link to pass the URL of the page you want them to return to.

So when they login, the variable is checked, if it is set, they are redirect to that page.

Something along those lines maybe?
<a href="login.php?redirect=mypage.php">
 
// Once they have logged in and the session set.
 
if(isset($_GET['redirect']){
 header("Refresh: 0; ./".$_GET['redirect']."");
}

Open in new window

0
 
cataleptic_stateAuthor Commented:
The link is called from a database as a city name http://localhost/site/search_by_location.php?rest_city=Birmingham%20Central

Will I be able to pass that detail over too? search_by_location.php?rest_city=Birmingham%20Central
0
 
wellsoCommented:
That would work fine if your script is ready to parse $_GET['rest_city'] into your database query.
0
 
cataleptic_stateAuthor Commented:
where do I put the js? in login.php? do I need to reference anything?
0
 
cataleptic_stateAuthor Commented:
I have this in login.php
<?php require_once('Connections/db.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  session_start();
}
 
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}
 
if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $password=$_POST['password'];
  $MM_fldUserAuthorization = "";
  $MM_redirectLoginSuccess = "index.php";
  $MM_redirectLoginFailed = "login_failed.php";
  $MM_redirecttoReferrer = true;
  mysql_select_db($database_db, $db);
  
  $LoginRS__query=sprintf("SELECT cust_username, cust_password FROM customers WHERE cust_username=%s AND cust_password=%s",
    GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
   
  $LoginRS = mysql_query($LoginRS__query, $db) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {
     $loginStrGroup = "";
    
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;	
	$_SESSION['logged'] = true;      
 
    if (isset($_SESSION['PrevUrl']) && true) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];	
    }
    header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>

Open in new window

0
 
wellsoCommented:
echoed In the else section
0
 
markloganCommented:
If the login link is to appear on

http://localhost/site/search_by_location.php?rest_city=Birmingham%20Central

You could do something like below to make the URL link. That will pass the URL via the URL

And after they have logged in redirect them using the header function and the redirect variable.
<a href="login.php?redirect=<?php echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>

Open in new window

0
 
wellsoCommented:
i think i misunderstood the question, sorry,
0
 
cataleptic_stateAuthor Commented:
Hi mark,
That code you gave is giving me problems with errors :'( And its made my login greeting disappear and just say welcome.

Where do I put the code you gave me?
0
 
markloganCommented:
Try the below code for the login link.
<a href="login.php?redirect=<?php echo $_SERVER['PHP_SELF']; if(isset($_SERVER['QUERY_STRING'])){echo "?".$_SERVER['QUERY_STRING']; } ?>">Login to see this</a>

Open in new window

0
 
markloganCommented:
And for the redirect
if(isset($_GET['redirect'])){
	header("Location: " . $_GET['redirect'] );
} else {
	header("Location: " . $MM_redirectLoginSuccess );
}

Open in new window

0
 
cataleptic_stateAuthor Commented:
im sorry there must be something im doing wrong. My table is in a echo statement and the redirect link your giving me does not liek it.
0
 
markloganCommented:
You just need to either change the format of the string or your if logged in statement.
<?php if ($_SESSION['logged'] == "true") { ?>
<table border="0">
	<tr>
		<td valign="top" class="JobText">Contact: <?php echo $row_job_results["rest_contact"]; ?></td>
        <td valign="top" class="JobText">Contact Number: <?php echo $row_job_results["rest_conttel"]; ?></td>
    </tr>
</table>
<?php } else { ?>
 
<table border="0">
	<tr>
		<td valign="top" class="JobText"><a href="login.php?redirect=<?php echo $_SERVER['PHP_SELF']; if(isset($_SERVER['QUERY_STRING'])){echo "?".$_SERVER['QUERY_STRING']; } ?>">login</a></td>
		<td valign="top" class="JobText"><a href="login.php?redirect=<?php echo $_SERVER['PHP_SELF']; if(isset($_SERVER['QUERY_STRING'])){echo "?".$_SERVER['QUERY_STRING']; } ?>">login</a></td>
	</tr>
</table>
<?php } ?>

Open in new window

0
 
markloganCommented:
Yes add it into the code you already have replacing the

header("Location: " . $MM_redirectLoginSuccess );

line.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.