send a value to another page when redirecting?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sigil
Forum Newbie
Posts: 5
Joined: Thu Apr 02, 2009 2:43 pm

send a value to another page when redirecting?

Post by sigil »

I want to have an error message on a page that comes up if the user entered something wrong (e.g., the wrong password).

The user starts at this page, call it index.php:

Code: Select all

<html>
<body>
<form action="action.php" method="post">
<input type="text" name="entrytext">
<input type="submit">
<?php
doSomething();
?>
</body>
</html>
At action.php:

Code: Select all

<?php
if goodInput($POST["entrytext"])
{
 doThis();
}
else
{
 doThat();
}
header("index.php");
?>
I want whatever happens in doSomething() on index.php to be affected by whether goodInput($POST["entrytext"]) in action.php was true or not. How can I have one page send a value to another page along with the header() redirect? There's no user entry happening on action.php, so I don't think I can use $POST to send a value back to index.php.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: send a value to another page when redirecting?

Post by JakeJ »

Try using a session. It's very easy to do. Your code would be as follows.

Code: Select all

//this is index.php
<?php session_start(); ?>
<html>
<body>
<form action="action.php" method="post">
<input type="text" name="entrytext">
<input type="submit">
<?php
doSomething();
?>
</body>
</html>
and

Code: Select all

<?php
session_start();
if goodInput($POST["entrytext"])
{
$_SESSION['something'] = "your text here" ;
doThis();
}
else
{
$_SESSION['something'] = "your other text here";
 doThat();
}
header("index.php");
?>
Then, when going back to index.php, you reference $_SESSION['something'] in whatever way you see fit and it's there.
sigil
Forum Newbie
Posts: 5
Joined: Thu Apr 02, 2009 2:43 pm

Re: send a value to another page when redirecting?

Post by sigil »

thanks, that solved the problem.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: send a value to another page when redirecting?

Post by JakeJ »

Glad I could help, I just learned how to use sessions myself very recently.

But always remember this, you always MUST start a session before there is ANY output. Therefore it's always safest to put it at the very top of the page under the <?php opening tag.
Post Reply