如何在PHP中正确使用$ _SERVER ['HTTP_REFERER']?
假设我有两个页面page1.php
和page2.php
,并且我希望仅当page2.php
从page1.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
:
-
在浏览器中操作非常简单.
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.