views:

91

answers:

2

Hello,

I am currently using PHP/MySQL, and I'd like to know the best way make an unauthenticated user login, and then have them automatically redirected to the page they logged in.

For example:

1) User tries to open up secure page.
2) They're re-directed and prompted to login.
3) After they login successfully, they're taken back to the URL they were trying to access.

Currently, on my "secure" pages, I have the following PHP code set up: (Not even sure if this is the proper way to do 'secure' it):

<?php
session_start();

 if ($_SESSION['first'] == "" && $_SESSION['usrID'] == "") {

    print" <script>
   window.location=\"../login/index.php\"
   </script> ";

    }

   ?>

Any suggestions on how to provide this feature (and possibly make my 'secure' code better), I'd greatly appreciate it.

Thanks!

+1  A: 

You can retrieve the referrer URI in the /login/index.php file and give it to the login form as a hidden field. And after user logs in you just redirect him to the page he was previously trying to access.

Something like that:

/login/index.php :

<?php

// if user submitted login form
if(isset($_POST['login'])) {

// do your login actions here
// and after...
header("Location: " . $_POST['returnto']);

}


//

$user_came_from = htmlspecialchars( $_SERVER['HTTP_REFERER'] );

?>
<form name="my_login_form" action="" method="post">
user: <input type="text" name="user" value="" />
pass: <input type="password" name="pass" value="" />
<input type="hidden" name="returnto" value="<?php echo $user_came_from ?>" />
<input type="submit" name="login" value="login" />
</form>
Rocko
+2  A: 

You could store the requesting URL in a session var.

$_SESSION['destination'] = $_SERVER['REQUEST_URI'];

Then, once logging in, you could do something like this:

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

    header('Location: ' . $_SESSION['destination']);
    exit;
}

Also, this isn't such a good idea

  print" <script>
   window.location=\"../login/index.php\"
   </script> ";

Using JavaScript to redirect has problems. For one, nothing will happen with JavaScript disabled. Try sending location headers

header('Location: ../login/index.php');
exit; // Call exit to make sure the rest of your code never executes
alex