SQLite as a PHP Session Handler

Now that I’ve discussed the in-memory data stores (NoSQL if you will) let’s switch gears to a more traditional RDBMS. SQLite by definition is a software library that implement a self-contained server-less, zero-configuration, transactional SQL database engine. It’s more important claim to fame is that it is the most widely deployed SQL database engine in the world (yes you read that right!).

Unlike MySQL which would require you to write a custom session handler provides an internal session handler for PHP (much like Memcached). As with other internal sessions handlers you have the choice of setting it in php.ini for all of your sites, or directly in your code on a per site (or even per script / per page basis). Before either will work you do need to be sure that you have the SQLite PHP extension installed and available. To set configure it in php.ini you simply set the following:

session.save_handler = sqlite
session.save_path    = '/path/to/sessions.db'

If you’d prefer to set SQLite as your session handler on a per site basis, just add this to the top of your scripts:

ini_set('session.save_handler', 'sqlite'
ini_set('session.save_path',    '/path/to/sessions.db'

I would place SQLite in between file-based sessions and in-memory sessions as it won’t be nearly as fast and reading and writing to RAM but is supposed to be faster than file-based sessions as well. Additionally, SQLite is not necessarily geared towards being used across a network (you’d have to use NFS and you will run into latency) so it doesn’t solve the multiple server problem with sessions. Full disclosure, I’ve never actually used SQLite as a session store, my preference these days is to use either file-based sessions or Redis depending on the size of the site.

So ends our week on PHP sessions and internal data stores. Seeing as I didn’t talk much about how to install the PHP Extension for SQLite, next week may be a week about installing that and some other popular PHP Extensions.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.