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

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

问题描述

我想根据用户操作将我的用户发送到不同的页面.所以我在页面顶部做了多个功能,如下所示:

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?

推荐答案

我想你误解了 HTTP 标头 Location 的作用.

I think you misunderstand what the HTTP header Location does.

Location 标头指示客户端导航到另一个页面.您不能在每页发送多个 Location 标头.

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

另外,PHP 在第一个输出之前发送标头.输出后,您不能再指定任何标头(除非您正在使用输出缓冲).

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

如果两次指定相同的标头,默认情况下,header() 将用最新的值替换之前的值...例如:

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');

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

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

Location 标头只能指定一次.发送多个 Location 标头不会将用户重定向到页面......它可能会混淆 UA 的废话.另外,请了解代码在发送 Location 标头后会继续执行.因此,按照对 header() 的调用,使用 退出.这是一个正确的重定向功能:

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天全站免登陆