开发者

Passing values between requests cleanly (in session, as GET/POST parameters... ?)

开发者 https://www.devze.com 2023-02-18 03:46 出处:网络
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:

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:

  1. How other programmers/platforms/frameworks handle this
  2. 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.

0

精彩评论

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

关注公众号