How to declare more than one header on PHP(如何在 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.php 或b.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 上声明多个标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PHP 上声明多个标头
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
