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

前端 未结 4 686
深忆病人
深忆病人 2020-12-18 17:11

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

4条回答
  •  青春惊慌失措
    2020-12-18 17:42

    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.

提交回复
热议问题