开发者

php variable persistance

I have two files:

index.php /lib/user.php

Index contains the form:

<div class="<? echo $msgclass; ?>">
  <? echo $msg; ?>
</div>
<form id="signin" action="/lib/user.php" method="post">
...
</form>

U开发者_如何学编程ser.php makes all the processing. It sets $msg to 'some error message' and $msgalert to 'error' in case of any error. At the end of processing it uses header() to redirect to index.php

But after redirection $msg and $msgalert no longer persist and index only gets empty vars. How can i fix this?


Edit: sorry misread your question. You can store those values in a session.

In /lib/user.php

session_start();
$_SESSION['msg']      = $msg;
$_SESSION['msgalert'] = $msgalert;

in index.php

session_start();
$msg      = $_SESSION['msg'];
$msgalert = $_SESSION['msgalert'];

note that session_start() uses headers so it must be put before any output is sent.


webpages are stateless. If you want to maintain state you either store the necessary values in a $_SESSION variable or pass it by $_GET or $_POST.


This is not a scope problem, it's a persistence problem. When you use header () to redirect, you're asking the browser to fetch an entirely different page, which executes an entirely different script.

You need to manually persist or pass the data, via database, session, $_GET variables, etc.


User.php and index.php are independent executions, so variable scope does not have much sense here.

You can pass those values by GET parameters or as session variables.

Try for example redirecting with a GET parameter:

header('Location: http://www.example.com/index.php?msgalert=error&msg=some%20error%20message');

And then in index.php use:

$_GET['msgalert']
$_GET['msg']

to access your data. Though if you can, using some predefined error messages hardcoded into the script would be better (passing only error codes).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜