如何在PHP中正确使用$ _SERVER ['HTTP_REFERER']? [英] How to use $_SERVER['HTTP_REFERER'] correctly in php?

查看:268
本文介绍了如何在PHP中正确使用$ _SERVER ['HTTP_REFERER']?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个页面page1.phppage2.php,并且我希望仅当page2.phppage1.php重定向并且我将此代码插入到page2.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 
}

此代码运行良好,直到单击提交按钮后,我在page2.php上有一个表单和一个提交按钮时,页面刷新,这意味着HTTP_REFERER将更改为page2.php,因此我的if statement失败并需要我回到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?

先谢谢了.

推荐答案

我不建议使用HTTP_REFERER:

  1. 在浏览器中操作非常简单.

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

某些用户可能在其浏览器中进行了安全设置,以致根本不发送此标头.

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

无法通过HTTPS访问.

某些代理从请求中删除了此标头

Some proxies strip this header from the request

已添加-请参见此问题的答案


如Charlotte Dunois在评论中所述,最好在发送表单之前设置会话值,然后在第2页上进行检查.


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;
}

使用isset( $_POST[ 'some_form_input' ] ),您可以检查表单是否已发送(通过POST方法).

With isset( $_POST[ 'some_form_input' ] ), you can check whether the form has been sent (via POST method).

在需要时,可以使用unset( $_SESSION[ 'display_page2' ] );或将其设置为其他值来取消设置会话.

When needed, you can unset the session with unset( $_SESSION[ 'display_page2' ] ); or by setting it to different value.

这篇关于如何在PHP中正确使用$ _SERVER ['HTTP_REFERER']?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆