2011-10-11

How to prevent sessions from expiring too quickly on PHP applications


When I started using sessions for authentication in a PHP web application I discovered that users were being logged out after a very short time.  After some research I discovered how sessions work in PHP.
A unique session ID is stored on a cookie on the users computer.  When the user connects to the server the server looks for a file with that unique session ID in its temp folder, and if one exists it pulls variable values from that file.  Every time any user connects to the server and starts a session the server generates a random number and then looks at some settings in php.ini to determine whether or not to clean out the temp folder. When it cleans out the temp folder it throws out session files older than the session.gc_maxlifetime setting in php.ini (set in seconds).  In order to enable keeping users logged in for long periods I set session.gc_maxlifetime = 1814400 in the php.ini.

This works on MAMP installations also. Just edit to /Applications/MAMP/conf/php5.3/php.ini

How to configure Apache in MAMP to only be accessible from the machine it is installed on

For a number of reasons I wanted to run a web application locally on my MacBook.  After some research I decided that the path of least resistance was to install the free MAMP app, which runs an Apache-MySQL-PHP stack on a Max OS X machine without having to do a complex install process.   I got my web app working on MAMP pretty easily, but then I discovered that other machines on my local network could also access the web app if they connected to the right port of the IP address of my MacBook.  That isn't a problem when I am at home or work, but I didn't want the web app exposed when I was on public networks like at a coffee house or the library.  After some research I discovered the solution was to edit the /Applications/MAMP/conf/apache/httpd.conf file to change:

Listen 8888

to

Listen 127.0.0.1:80

This did two things. It changed the port that MAMP uses from the MAMP default of 8888 to 80 (the normal web server port) and specified that only traffic from the local machine would be accepted.  After I made this change and restarted the Apache server I was no longer able to access the web app from other machines on the same network.