douyan1970 2012-11-17 21:23
浏览 65
已采纳

如何在mysql表中生成引用会话的唯一会话密钥?

I was using $_SESSION to store users IDs but I want to change to using a regular cookie (with a KEY) paired with SQL so I can keep users authenticated when they close their browsers.

How do I create an unique key for each row in my SESSIONs table?

  • 写回答

3条回答 默认 最新

  • douzheng5717 2012-11-17 21:36
    关注

    You're effectively looking to write your own session handler to bypass PHP's cookie expiration issue on session cookies. This is pretty straightforward, and pretty optimized if done properly.

    Step 1: generating the session ID

    A session ID is unique. However, if you're planning for permanent sessions, you have to bear a couple of things in mind: you want the session to carry over per browser, regardless of connection issues. So, you can cheat the system a bit by mapping the session ID with the user agent of the navigator (which doesn't change).

    This allows you to reduce the chance for your session ID generator to generate the same ID for two distinct visitors. The rest is up to a random number generator and a hash algorithm, though - md5(microtime().$_SERVER['REMOTE_ADDR']) is usually a trusted friend.

    Step 2: storing and retrieving the data

    Storing the data is also trivial. Your aim is to create a MySQL table with a minimum of two columns: the session key (set to PRIMARY), and the data (serialized array for the simplest form, stored as TEXT).

    When you create a session, just insert a new row and watch for errors. If an error comes up, the key was already used, so you'll need to re-generate another. If the row was inserted successfully - all good, you now have a session row for the user! All you need to do from there on is to read/write to this row as you see fit.

    Cookie the user with the session ID, and you're done!

    Caveats

    • Never ever use a userID as session ID. Cookies can be very easily manipulated. You want the cookie value to be random and completely separated from the user. It should be meaningless.
    • You'll need to write clean-up code to clean up the session table from time to time. A good way to do this is to keep track of when a session was last used - and delete accordingly.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计