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

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

假设我有两个页面 page1.phppage2.php,我希望 page2.php 仅在从 page1.php 重定向时显示,我将此代码插入到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 我不希望这种情况发生。有什么办法可以防止这种情况发生吗?

提前致谢。

我不推荐使用 HTTP_REFERER:

  1. 在浏览器中操作起来相当简单。

  2. 某些用户可能在他们的浏览器中进行了安全设置,根本不发送此 header。

  3. 无法通过 HTTPS 访问。

  4. 一些代理从请求中删除此 header

  5. 已添加 - 查看 this quesion

  6. 的答案

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

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方法)。

需要时,您可以使用 unset( $_SESSION[ 'display_page2' ] ); 或将其设置为不同的值来取消设置 session。

<?php
if(($_SERVER['HTTP_REFERER'] == "page1.php") || (isset($_POST['submit']) && $_SERVER['HTTP_REFERER']=="page2.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 
}

?>

如果 referrer 不是第 1 页,您可以检查是否提交了 referrer = page2 和 post。 或检查引荐来源网址是否为 page1 或 post 已提交。 这是避免您的问题的可能性。

我建议不要使用 $_SERVER['HTTP_REFERER'],因为它很容易被欺骗。

相反,您可以在他们加载第 1 页时使用 setcookie("page1", 1); 输出任何标记之前设置 cookie。然后在第 2 页使用

检查它
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 
}

如果不指定失效日期,cookie 将在浏览器关闭时失效。在这种情况下,使用 cookie 还可以为其他人提供更易读的代码。

<?php

/* 
    this page allows links from the following pages

    public.php?id=links
    private.php?id=links

don't allow if visitors come from anywhere else

this example would only work if I used the entire URL in the 'if' statement 
*/

$referringpage = $_SERVER['HTTP_REFERER'];

if ( $referringpage == "http://www.example.com/public.php?id=links" ) {
$pass = "yes";
} elseif ( $referringpage == "http://www.example.com/private.php?id=links" ) {
$pass = "yes";
} else {
$pass = "no";
}


if ( $pass == "yes" ) {
// do the function this page was made to do
} 

header( "Location: http://www.example.com/public.php?id=links" );

?>