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?
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?
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