Joca Baldini
Joca Baldini

Reputation: 43

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

In my website the index will redirect to a controller that will access the DAO and needs set the data in a variable to show in the view. How do i set this datas? Is the $_SESSION the best way to do that?

I try the $_REQUEST, making this:

(Index.php)

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

(controllerIndex.php)

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

But i received the error:

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

Upvotes: 3

Views: 3185

Answers (3)

RiggsFolly
RiggsFolly

Reputation: 94682

Using $_SESSION is probably the best solution, but the other option would be to just add the parameters to your header() url and they will be passed in the $_GET array.

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

Or without the Framework idea

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

Upvotes: 1

Scott
Scott

Reputation: 1922

As mentioned already, PHP SESSION variables are the solution you're looking for. It is important that you include session_start(); at the top of each PHP page that requires access to the session variable. Take a look at this which should help with your problem:

Index.php

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

Controller.php

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

Upvotes: 2

Bryant Frankford
Bryant Frankford

Reputation: 391

You answered your own question, $_SESSION would be better.

You can also unset all your $_SESSION variables as described here http://php.net/manual/en/function.session-unset.php

Upvotes: 1

Related Questions