Link to home
Start Free TrialLog in
Avatar of iManu
iManu

asked on

Redirecting from login to original page

How do I redirect a user back to the original page that he clicked on and was redirected to log in to view that page and upon login should be able to view the original page? It shouldnt be only for session timeouts causing it, but in a general manner.

This is what I require:
User Clicks faq.php  - if(authorized) views that page else redirected to login page...after login, should be able to see faq.php.
Avatar of Kani Str
Kani Str
Flag of India image

use 'HTTP_REFERER'

when the user cick on faq.php, if not authorized you direct him to login.php so
$_SERVER['HTTP_REFERER'] will be set to faq.php ,

After the user logs in refer $_SERVER['HTTP_REFERER'] you will get the last page ..

the redirect to that page..
using
header("location:".$_SERVER['HTTP_REFERER']);

this works depends on how many redirects you are using in between the pages !!!

This is a little clue how we can acheive this.  

There are some other ways like passing values via querystring also possible. But I think  this is a easier one.
Avatar of iManu
iManu

ASKER

I have tried using HTTP_REFERER, but there seems to be some problem with it...its redirecting to the base folder instead...though didnt dig much into it, but still some other way is better.
when you click on faq.php, you enters faq.php and check whether the user logged in or not. If not     redirects to the login page right?
at this point add a query string value like login.php?from=faq

then the user successfully enter username & pass. take him to the faq.php using the value in the querystring.
Avatar of iManu

ASKER

Could you post the code for redirecting? I have query strings passed...but they arent showing up...may be because am redirecting using ' location:', the query string is not being passed.
istead it will be easy if you paste your code.. here let's find why that's not working... Need not to paste full code. Only the code we are talking about..

Avatar of iManu

ASKER

every page that leads to login has a query string like login.php?redirect=faq.php


Login page:

$redir = $_GET[redirect];

if(!$redir)
{
die( header('location: account.php?id='.session_id()) );
exit();
}
else
{
die( header('location: '.$redir) );
exit();
}
Just try the following code....

if(!isset($_GET['redirect']))
{
  header('location: account.php?id='.session_id());
  exit();
}
else
{
 $redir = $_GET['redirect'];
// for checking
 echo $redir;
 header('location: '.$redir);
 exit();
}
Avatar of iManu

ASKER

i dont know, but its redirecting to the base folder as I had mentioned earlier. Can that be a problem because am running on my computer and while on server, it wont give that problem?
what did that
echo $redir produced?

if you are running on a internet webserver, please give me the link, I check it out.
Avatar of iManu

ASKER

its blank..that means that $redir is empty...actually am starting a session after $redirect is captured...will that affect it?
That why it's taken you to the base folder.

>>>actually am starting a session after $redirect is captured...will that affect it?

No it won't.

Are you able to see the query string and it's value in the URL box of the browser ?



Avatar of iManu

ASKER

yea...the query string is visible in the address box....even I printed $redir before starting the session and its printing...but after login, its not printing.
good move.

Let's take a chance...
{
 Get querystring  value here...
 redirect  to faq
 then start session
 exit;
}

The session will be started even after redirected, so there will be no problem. Don't forget the exit after starting the session.
make sure the single quote ON like

$redir = $_GET['redirect'];
Avatar of iManu

ASKER

That isnt working either....is that a problem with variable scope or something?
Avatar of iManu

ASKER

Can someone tell any other way of keeping track of the query string and then redirect to the correct pages OR try to rectify the above code?
SOLUTION
Avatar of Kani Str
Kani Str
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> when the user cick on faq.php, if not authorized you direct him to login.php
> so $_SERVER['HTTP_REFERER'] will be set to faq.php ,

You don't need to use referrer. I'd usually do it like this (in faq.php):

<?php
session_start()
if (!$_SESSION['loggedin']) {
  header('Location: login.php?return={$_SERVER['PHP_SELF']}");
  exit();
}
?>

Then in login.php, after login details are authenticated:

$_SESSION['loggedin'] = true;
if (array_key_exists('return', $_GET)) {
  header("Location: {$_GET['return']}");
  exit();
} else {
  header('Location: default.php');
  exit();
}

There is no point in starting the session after you redirect. Putting your redirect in a call to die() is also a strange thing to do. If you echo anything before you issue the redirect, the redirect will not work and you'll get a 'headers already sent' error.
Avatar of iManu

ASKER

str_kain: I know the above thing should be working...but its not working on my computer as well as the host's web server.

Squinky: This one is almost similar to the one I tried out...anyway thanks for trying.


Here's the whole code:

<?

$email = $_POST["email"];
$pwd = $_POST["password"];

if($email || $password)
{
// Connecting, selecting database
$conn = mysql_connect('localhost', 'myhost', 'pwd') or die('Could not connect: ' . mysql_error());
mysql_select_db('mydb) or die('Could not select database');

// Performing SQL query
$query = "SELECT * FROM customers where email='$email' and password='$pwd'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

$num = mysql_num_rows($result);


if ($num==0)
{
echo "<font color='red'>Invalid User Name or Password!</font><Br>";
}
else
{

$fields =  mysql_fetch_row($result);
session_start();
$_SESSION['email'] = $fields[2];
$_SESSION['noq']=$fields[4];


if (!array_key_exists('return', $_GET)) {
  header("Location: {$_GET['return']}");
  exit();
} else {
  header('Location: account.php');
  exit();
}

}

}

?>
coule you please post a link here to check it out... ?
It doesn't help if you don't tell us exactly how it's not working, show error messages.

There's a missing quote in this line:

mysql_select_db('mydb) or die('Could not select database');

Other minor things:
Check for the existence of email and password fields using array_key_exists('email', $_POST), and there's no particular reason to copy them into local variables.
It's a good idea not to store passwords directly but a hash of them instead.
You're doing a select * in your query, and then extracting items using numeric index. This is an error-prone combination. If you're going to use *, get fields by name. If you want to use numbers for speed, then list the field names you want in your query, e.g. "SELECT email, noq FROM ..." so it's clear in the code alone (without reference to the DB structure) what will be in the $fields array.
Avatar of iManu

ASKER

You can check it out at:

http://csonweb.uni.cc/trac or http://manu.neil-shah.net/trac

the username: manu_cs45@yahoo.com and password: manu
1) Do one thing, don't pass the full path in the query string.... like this.
        http://manu.neil-shah.net/trac/login.php?return=/trac/faq.php
instead try like         http://manu.neil-shah.net/trac/login.php?return=faq.php
Avatar of iManu

ASKER

str_kani: Is the second method working for you? Am unable to get back to faq.php even if I use the second one...i.e login.php?return=faq.php...its taking to the root folder again.

Squinky: Sorry, the missing quote was a typo I guess...and that password field doesnt exist...regarding the fields...its not wrong in any sense though I need to retrieve the correct index...and thats not what I am looking for....only the redirection to be correct...does those have anything related to the improper redirection?
Well it's hard to tell - you should be testing them independently because at the moment you can't tell which bit is broken. The things I pointed out are possible sources of error - because your redirection is at least partly dependent on you getting your array indices right, it just seems sensible to use them in such a way that it's clear that they are not the problem - this is why I suggest that you program defensively. It would be very easy to test that the redirection itself is working by doing a simple hard-coded example that skips the authentication (just says it was ok), as it may simply be that errors in your database lookup are causing the problem and that your redirects are fine.
It seems it takes to the root but doesn't take over to the page specified... try with these lines....

$red="http://manu.neil-shah.net/".$_GET['return'];
header("location:$red");


This takes me, I am running my code here. This will help you ..:)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This approach will also work if the user fails the login a few times before succeeding - they will still be redirected to the correct place once they get in.
Avatar of iManu

ASKER

Well, its redirecting only to the second page although there are query strings...you can check out at http://csonweb.uni.cc/trac
Ah, dumb typo near the end:

if (array_key_exists('return', $_SESSION)) {
Avatar of iManu

ASKER

Yea...I just realised and its working now...thanx a lot...both of you for your quuick responses and great assistance.
Glad to hear you got the solution :)