drzb7969753 2016-03-26 19:52
浏览 98
已采纳

如何在PHP中正确使用$ _SERVER ['HTTP_REFERER']?

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.

  • 写回答

4条回答 默认 最新

  • dongniechi7825 2016-03-26 20:02
    关注

    I wouldnt 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题