I don't like having to explicitly manage values in session and I can't imagine I'm alone in this... so I wanted to get feedback on:
- How other programmers/platforms/frameworks handle this
- The method I use (explained below)
The method I use involves a controller-type script that supports adding a variable in session when I know it may be needed in the next request... and automatically removes it afterwards (the TTL is controlled through a counter).
For example,
- Request 1 - script adds a value to the session with key
selectedValue
- Request 2 - script reads
selectedValue
from the session - Request 3 -
selectedValue
is gone from the session (this is OK because it's no longer needed)
This is the cleanest way I can think of passing values through different requests, as opposed to storing global variables in session (e.g., an authenticated user ID).
In this scenario, a page refresh is ignored, and if a value needs to be passed through to further requests, it nee开发者_如何学Gods to be set again.
Instead of storing it in the session, you could also just pass it as a request parameter to the subsequent request. Assuming that you're using forms for this, the <input type="hidden">
useful for this.
E.g.
<form action="confirm.php" method="post">
<input type="submit" name="confirm" value="Confirm" />
<input type="hidden" name="foo" value="<?=htmlspecialchars($foo)?>" />
</form>
You can retain it by $_POST['foo']
then.
I went the hidden field route after having bad experiences debugging $_SESSION related issues, however now that I'm more experienced I think session variables are the better way to go. I'd rather explicitly manage values in $_SESSION than do essentially the same thing with hidden fields where you have to re-encode that information at every page load if you want to retain it over multiple refreshes.
精彩评论