Storing encrypted session information in a cookie
Our session system is due for an upgrade. Currently all PHP sessions are stored in the database, and some things are getting a bit slow. There have been a couple of approaches I've been considering, one of which is simply storing all the information in a browser cookie.
First I want to make clear I don't necessarily condone this. The reason I'm writing this post, is because I'm hoping for some more community feedback. Is this a really bad idea? I would love to know.
The benefits
If all the session data is stored in the browser, it means that I don't need to store it on the server. I actually don't care all that much for having the data on the server (unless it's the only secure way), it's mostly a gigantic map with session tokens and user id's (along with some other info).
I also feel it's more natural for HTTP, as it makes it a bit more stateless.
Sample code
- A
- class BrowserSession {
- A
- A A public $secret = 'this will need to be a cryptographic random number';
- A A public $currentUser = null;
- A
- A A // Sessions time out after 10 minutes
- A A public $timeout = 600;
- A
- A A function init() {
- A
- A A A A if (!isset($_COOKIE['MYSESSION'])) {
- A A A A A A echo "No session cookie found\n";
- A A A A A A return;
- A A A A }
- A
- A A A A list($userId, $time, $signature) = explode(':',$_COOKIE['MYSESSION']);
- A A A A
- A A A A // The cookie is old
- A A A A if ($time time() + $this-timeout) {
- A A A A A A echo "The session cookie timed out\n"
Truncated by Planet PHP, read more at the original (another 10267 bytes)


