PHP 如何使用 header(重定向)将数据发送到另一个页面

PHP How to send data to another page with header(redirect)

在我的网站中,索引将重定向到一个控制器,该控制器将访问 DAO 并需要在变量中设置数据以显示在视图中。我如何设置这些数据? $_SESSION 是最好的方法吗?

我尝试 $_REQUEST,使这个:

(Index.php)

<?php
$_REQUEST['test'] = "TEST!!!!";
$redirect = "controllers/controllerIndex.php";
header("location:$redirect");

(控制器Index.php)

<?php
echo $_REQUEST['test'];

但我收到错误消息:

Notice: Undefined index: test in C:\xampp\htdocs\PlataformaPHP\controllers\controllerIndex.php on line 2

你回答了你自己的问题,$_SESSION会更好。

您还可以按照此处所述取消设置所有 $_SESSION 变量 http://php.net/manual/en/function.session-unset.php

如前所述,PHP SESSION 变量是您正在寻找的解决方案。在每个需要访问会话变量的 PHP 页面的顶部包含 session_start(); 很重要。看看这个应该可以帮助您解决问题:

Index.php

<?php
    session_start();
    $_SESSION['test'] = "TEST!!!!";
    $redirect = "controllers/controllerIndex.php";
    header("location:$redirect");
    exit();
?>

Controller.php

<?php
    session_start();
    echo $_SESSION['test'];
    ...
?>

使用 $_SESSION 可能是最好的解决方案,但另一种选择是将参数添加到 header() url 中,它们将在 $_GET 数组中传递.

$redirect = "controllers/controllerIndex/test";
header("location:$redirect");

或没有框架想法

header("Location: xxx.php?test");