views:

398

answers:

3

Hi all,

For example,

STEP 1:

I am browsing a page without logging in and my last page before logging in is beforeLogin.php

STEP 2:

Now my prob is when i logged in i am redirecting to the index.php page. Instead i should be redirected to the last page what i had browsed.

That is from the above example is should redirected to beforeLogin.php

How should this can be done.

Any help will be appreciable.

thanks in advance

+4  A: 

You would need a way to keep track of the web pages visited, so you can back-reference to the last page the user has browsed to.

When I think of tracking a user's session across multiple-pages I, like every other PHP programmer, think of using sessions.

A possible way could be to store the link visited into a session variable and then when the user reaches the login.php page (the page to login into) provide a header redirect to $url given by the session variable.

NOTE: Below code snippets, have not been tested or compiled.

You can paste this code into all your pages on your website:

<?php
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI']; // i.e. "about.php"

This utilizes the $_SERVER variables to return the URI of the current page visited using $_SERVER['REQUEST_URI']

And then for the login page to help further demonstrate:

<?php
session_start();  // needed for sessions.
if(isset($_SESSION['url'])) 
   $url = $_SESSION['url']; // holds url for last page visited.
else 
   $url = "index.php"; // default page for 

header("Location: http://example.com/$url"); // perform correct redirect.
Anthony Forloney
+1  A: 

you can make login form action lead to the current page. that's plain and simple

Say, your page looks like

<?
include "auth.php"; // you need it anyway, as you want to control user's auth
//the rest of the page;
?>
<form method="POST">
login form
</form>
<?
//the rest of the page;
if (!empty($_SESSION['user_id'])) echo "Welcome registered user!";
?>

and auth.php would take care of login check and then redirect to a current page is not a big deal

<?
if (isset($_REQUEST[session_name()])) session_start();
if (isset($_POST['auth_name'])) {
  //password checking
  if (pass ok) {
    session_start();
    $_SESSION['user_id'] = $row['id'];
  }
  header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
  exit;
}

something like this no extra session required.

Col. Shrapnel
+1  A: 

The simplest solution by far is simply to have:

<hidden name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />

Then redirect to that address once they log in.

However, this is only good if you have a login box on every page. I personally do and I find it works quite well.

Lotus Notes