Reputation: 844
There are lot of relavent questions with many answets to this but i wanted to know what is the best and suggested method for this.
The question is simple.i wanted to redirect from one page to other when a condition is not met and after this condition became true in the redirected page,return to the same page from where the redirect is requested in a php or jsp page
More relavent example would be : when a user wants to buy a product from a website,when he chooses a product and want to make payment, the site checks whether the user has log in to the site. If not it takes to login page,and after logging in,take the user to the payment page directly rather than some homepage which usually the login page takes to.
There were options like storing sessions and storing the requested url in a session variable and then use this to return to the page.
But my question is to find what is the most suitable standard for this. Detailed answers are appreciated. Thanks in advance.
Upvotes: 3
Views: 1289
Reputation: 2280
You can do it like this way :
First you need to get the current page dynamically so in PHP we have $_SERVER
to do the job So we can use following code to get our current PHP Page name :
$redirect_page = basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */
Note : You will only get the current PHP File name not exactly the whole URL using the above code.
Then we need to use something in which we can store the value in order to be able to use it on the next redirected page so we have COOKIES & SESSIONS in PHP to do the job and here I am going to share both methods with you.As we already got our page name so second we need to store it.
We can create a cookie like this way :
setcookie("redirect_page", $redirect_page, time()+20);
As you can see we created a cookie here and stored the redirect page name in it.
Now when you redirect to another like this way by using header
:
header("Location: 2nd_page.php");
And on the 2nd Page you can redirect page to the first page from where you were being redirected like this way :
if ($value1 != $value2) {
$redirect_back = $_COOKIE['redirect_page'];
header("Location: $redirect_back");
}
We can create a session like this way :
$_SESSION['redirect_page'] = $redirect_page;
As you can see we created a cookie here and stored the redirect page name in it.
Now when you redirect to another like this way by using header
:
header("Location: 2nd_page.php");
And on the 2nd Page you can redirect page to the first page from where you were being redirected like this way :
if ($value1 != $value2) {
$redirect_back = $_SESSION['redirect_page'];
header("Location: $redirect_back");
}
Note : Remember to run the session_start()
statement on both these pages before you try to access the $_SESSION
array, and also before any output is sent to the browser.
Upvotes: 2