如何在PHP上声明多个头文件 [英] How to declare more than one header on PHP

查看:158
本文介绍了如何在PHP上声明多个头文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据用户操作将我的用户发送到不同的页面。因此,我在页面顶部创建了多个功能,如下所示:

 <?php 

function one(){
header(location:pagea.php);
}
函数two(){
header(location:pageb.php);
}
函数three(){
header(location:pagec.php);
}

?>

当然,我得到一个错误,因为我正在声明头文件。起初我虽然会好起来的,因为我将它们包含在函数中,并且一次调用任何一个函数。但我仍然得到错误。有没有其他的方法可以做到这一点?解决方案

我认为你误解了HTTP头 Location



位置标题指示客户端导航到另一个页面。您不能在每页发送一个 Location 标题。

另外,PHP在第一个输出之前发送标题。一旦你输出了,你就不能指定任何更多的头文件(除非你使用输出缓冲)。

如果你指定了两个相同的头文件,默认情况下 header() 会用最新的值替换之前的值...例如:

 <?php 
header('Location:a.php');
header('Location:b.php');
header('Location:c.php');

会将用户重定向到 c.php ,永远不会传递 a.php b.php 。您可以通过向第二个参数(称为 $ replace )传递 false 值来覆盖此行为:

 <?php 
header('X-Powered-By:MyFrameWork',false);
header('X-Powered-By:MyFrameWork Plugin',false);

Location 标题只能指定一次。发送多个 Location 标题不会将用户重定向到页面......这可能会让UA中的垃圾混淆。此外,请理解,在发送位置标头后,代码会继续执行。因此,请使用 header() 进行调用。 href =http://php.net/exit =noreferrer> exit 。这里有一个合适的重定向函数:

pre $ 函数重定向($ page){
header('Location:'。$页);
出口;
}


I want to send my users to different pages based on user action. So I made multiple functions at the top of the page like so:

<?php

function one() {
     header("location: pagea.php");
}
function two() {
     header("location: pageb.php");
}
function three() {
     header("location: pagec.php");
}

?>

Of course I get an error because I am re declaring headers. At first I though it was going to be okay since I am containing them inside functions and am calling any one function at a time. But still I get the error. Is there any other way of doing this?

解决方案

I think you misunderstand what the HTTP header Location does.

The Location header instructs the client to navigate to another page. You cannot send more the one Location header per page.

Also, PHP sends headers right before the first output. Once you output, you cannot specify any more headers (unless you are using Output Buffering).

If you specify the same header twice, by default, header() will replace the previous value with the latest one... For example:

<?php
header('Location: a.php');
header('Location: b.php');
header('Location: c.php');

will redirect the user to c.php, never once passing by a.php or b.php. You can override this behavior by passing a false value to the second parameter (called $replace):

<?php
header('X-Powered-By: MyFrameWork', false);
header('X-Powered-By: MyFrameWork Plugin', false);

The Location header can only be specified once. Sending multiple Location header will not redirect the users to the pages... It will probably confuse the crap out of the UA. Also, understand that the code continues to execute after sending a Location header. So follow that call to header() with an exit. Here is a proper redirect function:

function redirect($page) {
    header('Location: ' . $page);
    exit;
}

这篇关于如何在PHP上声明多个头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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