Reputation: 1221
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?
Upvotes: 1
Views: 206
Reputation: 51200
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
<?php
if (!$authenticated) {
header("Location: /LoginView.php?r=ProtectedPage.php");
}
?>
<form action="LoginAction.php" method="post">
<input type="hidden" id="r" value="<?php echo $_GET['r'] ?>" />
...
</form>
<?php
... Authenticate the user ...
if (!empty($_POST['r'])) { header("Location: {$_POST['r']}"); }
else { header("Location: /"); }
?>
Upvotes: 2
Reputation: 43619
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
}
?>
Upvotes: 4