views:

62

answers:

2

How do I remember a url in php to serve it to a user after authentication. The idea is the user will request the url but while unauthenticated. In this case, I forward him to the login page, but what's the best practice to save that url so I can serve it to him once authenticated. I thought about saving it in session variables, but not sure about the implementation. Are there best practices for this?

+4  A: 

Put it in a hidden field in the form or save it to a session variable.

Example

login.php?l=account.php (where l is the page to go after login).

<form action="action/login.php" method="post">
<input type="hidden" value="<?php echo $_GET['l'] ? $_GET['l'] : 'index.php'; ?>" name="redirect" />
...
</form>

action/login.php

<?php

  ... do some checking here...

  if($loggedin){

    redirect($_POST['redirect']);
    // redirect() a wrapper function for header("Location: $url");

  }else{

    redirect('login.php?l='.$_POST['redirect']);
    // go back to login page

  }

?>
thephpdeveloper
Preferably the former. Sessions will cause troubles (redirect to the wrong URL) if the user opens multiple login forms from different locations.
Lukáš Lalinský
And of course *NEVER* output raw user input into your HTML. :) use `htmlspecialchars()` on it.
Lukáš Lalinský
The only issue here is that most people like to automatically redirect to the login page
Joe Philllips
yep correct, never output raw user input!
thephpdeveloper
@Lukas - Great point. Twitter uses a session, and it's a usability nightmare if I open a bunch of links in tabs that all require login - I lose all but the last one.
ceejayoz
+1  A: 

When the user goes to ProtectedPage.php without being authenticated, this should automatically redirect them to LoginView.php (with the previous page's URL attached). They can then proceed to login and the LoginAction.php page will redirect them back to the ProtectedPage.php

ProtectedPage.php

<?php
    if (!$authenticated) {
        header("Location: /LoginView.php?r=ProtectedPage.php");
    }
?>

LoginView.php

<form action="LoginAction.php" method="post">
<input type="hidden" id="r" value="<?php echo $_GET['r'] ?>" />
...
</form>

LoginAction.php

<?php
    ... Authenticate the user ...

    if (!empty($_POST['r'])) { header("Location: {$_POST['r']}"); }
    else { header("Location: /"); }
?>
Joe Philllips