Now that we know how to use sessions and have built a simple login system, let’s take a look at some options for configuring PHP sessions.
Out of the box, PHP is configured to file-based sessions with a max lifetime of 1440 seconds (a mere 24 minutes). Garbage collection probability is set to 1/100 or 1% of the time. As of PHP 5 you can set the hash function that’s used but it’s set to MD5 (128-bits) by default with no entropy file (unless you’re on 5.4+ which sets it to /dev/urandom
or /dev/arandom
.
These settings will do fine for many scenarios, but what if you want sessions to last longer or perhaps up your session security a bit? To accomplish these things you will either want to make changes to your php.ini
or by way of the ini_set()
function in your code.
session.gc_maxlifetime
This is how long a session has to live before the garbage collection routine will purge it. I generally set this to 86400 (24 hours) on websites where I know users log in every day.
session.gc_probability and session.gc_divisor
Is garbage collection 1% of the time too often or not enough for your taste? If that’s the case, you can make a change to session.gc_divisor
to run it less often (increase the value) or more often (decrease the value). The probability of garbage collection is calculated as session.gc_probability / session.gc_divisor
.
session.hash_function
As mentioned, the default hash function is MD5, but what if we wanted something a bit longer to add more complexity to the session ID? If that’s the case you can set the hash function to 1 which will tell it to use SHA-1 which is 160-bits. Since PHP 5.3 you can specify any of the registered hash functions returned by hash_algos()
.
session.name
Speaking of session names, by default PHP session ID’s are prefixed with PHPSESSID
. To help combat against someone attempting to hijack a domain by guessing session ID’s, you could change the name to something unique and less guessable.
session.entropy_file and session.entropy_length
If you’re running Ubuntu 12.04 LTS like me you probably are still using PHP 5.3 which by default doesn’t set these values. The entropy file is what is used to seed the session ID generator and the length is how many bits will be read for the seed. You can specify any program to be used as the seed, I usually go with /dev/urandom
with a length of 512.
And all the rest
There are more configuration options out there as I only covered the configuration options I’ve interacted with before. If you are interesting in learning about all of the available options, you can find them here.