Caching variables in the $_SESSION variable?

后端 未结 3 1737
暗喜
暗喜 2021-02-14 16:09

I\'m making a php web application which stores user specific information that is not shared with other users.

Would it be a good idea to store some of this information i

相关标签:
3条回答
  • 2021-02-14 16:19

    That could work well for relatively small amounts of data but you'll have to take some things into consideration:

    1. $_SESSION is stored somewhere between requests, file on disk or database or something else depending on what you choose to use (default to file)
    2. $_SESSION is local to a single user on a single machine.
    3. sessions have a TTL (time to live), they dissapear after a set amount of time (which you control)
    4. Under certain circumstances, sessions can block (rarely an issue, but i've run into it streaming flash) If the data you mean to cache is to be accessed by multiple users you're quickly better off caching it seperately.
    0 讨论(0)
  • 2021-02-14 16:30

    If you only want this data available during their session, then yes. If you want it available tomorrow, or 4 hours from now, you need to save it to a database.

    Technically you can modify the sessions to have a very long lifespan, but realize if they use a different computer, a different browser or flush their cookies they will loose the link to their session, therefore anything serious you should create a type of user account in your application, link the session to their account and save the data in a permeate place.

    0 讨论(0)
  • 2021-02-14 16:43

    This would be an appropriate use of the session mechanism as long as you keep this in mind:

    • Session does not persist for an indefinite amount of time.
    • When pulling from session, ensure you actually got a result (ASP.NET will return NULL if the Session has expired/cleared)
    • Server restarts may wipe the session cache.
    • Do this for convenience, not performance. For high-performance caching, choose an appropriate mechanism (i.e. memcached)

    A good usage pattern would be like this (ether cookies or session):

    • User logs in
    • Store preferences (background color, last 10 records looked at, categories) in session/cookie.
    • On rendering of a page, refer to the Session/Cookie values (ensuring they are valid values and not null).

    Things not to do in a cookie

    • Don't store anything sensitive (use session).
    • A cookie value should not grant/deny you access to anything (use session).
    • Trap errors, assume flags and strings may not be what you expect, may be missing, may be changed in transit.

    I'm sure there is other things to consider too, but this is just off the top of my head here.

    0 讨论(0)
提交回复
热议问题