Lets say i have two pages page1.php and page2.php and i want page2.php to be displayed only if it is redirected form page1.php and i inserted this code to page2.php
if($_SERVER['HTTP_REFERER'] == "page1.php")
{
//keep displaying page2.php
}else{
//if it is not redirected from page1.php
header('Location:page1.php')
//redirect the user back to page1.php
}
this code worked fine until i have a form and a submit button on page2.php when the submit button is clicked the page refreshes which means the HTTP_REFERER will change to page2.php so my if statement fails and it takes me back to page1.php i don't want that to happen. Is there any way to prevent this from happening?
Thanks in advance.
I wouldn't recommend using HTTP_REFERER:
It's fairly simple to manipulable in browser.
Some users might have security settings in their browser to not send this header at all.
It's not accessible over HTTPS.
Some proxies strip this header from the request
Added - See answer to this quesion
As Charlotte Dunois stated in the comment, better set session value before sending the form and then check it on page2.
page1.php:
$_SESSION[ 'display_page2' ] = TRUE;
//rest of the content
page2.php:
if ( (isset( $_SESSION[ 'display_page2' ] ) && $_SESSION[ 'display_page2' ] === TRUE ) || isset( $_POST[ 'some_form_input' ] ) ) {
//keep displaying page2.php
} else {
header('Location:page1.php');
exit;
}
With isset( $_POST[ 'some_form_input' ] ), you can check whether the form has been sent (via POST method).
When needed, you can unset the session with unset( $_SESSION[ 'display_page2' ] ); or by setting it to different value.
I advise against using $_SERVER['HTTP_REFERER'] as it can be easily spoofed.
Instead , you could set a cookie when they load page 1 using setcookie("page1", 1); before any markup is output. Then check for it on page 2 using
if(isset($_COOKIE['page1']))
{
//keep displaying page2.php
}else{
//if it is not redirected from page1.php
header('Location:page1.php')
//redirect the user back to page1.php
}
By not specifying the expiry date the cookie will expire when the browser is closed. In this situation, using cookies also makes for much more readable code to others.
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