I have a page named Login.php
. I need the URL of the page before the last page.
When the user login form will submit to check_login.php
which checks their username and password. Then I will redirect the user to index.php
.
The issue is I want the user to be redirected to the second to last page they visited.
EXAMPLE:
First URL: www.example.com/posts/1
Second URL: www.example.com/login.php
Third URL: wwww.example.com/check_login.php
So, if username and password are correct => header('location: www.example.com/posts/1');
There is a solution to get the previous URL:
// login.php
$_SESSION['url'] = $_SERVER['HTTP_REFERER'];
// check_login.php
header('location: '.$_SESSION['url']);
But I need to get the second to last URL, not the last URL. How can I do this in PHP?
Do what other people have done:
First solution:
Create a hidden
field in your pages so that when a user clicks on login
it will take him to the login.php
page with the previous link. Then you can do anything you want (like, saving it to $_SESSION['url']
) with this link.
Second Solution:
Imagine you have an anchor like this:
<a href="login.php">login</a>
.
Instead of using just login.php
you can use login.php?redirect_to=http://example.com/post/1
so that you can access the url from your login.php
page with a $_GET['redirect_to']
request.
NOTE: Always remember to sanitize user input data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With