Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
859 views
in Technique[技术] by (71.8m points)

redirect - How to use $_SERVER['HTTP_REFERER'] correctly in php?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wouldn't recommend using HTTP_REFERER:

  1. It's fairly simple to manipulable in browser.

  2. Some users might have security settings in their browser to not send this header at all.

  3. It's not accessible over HTTPS.

  4. Some proxies strip this header from the request

  5. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...