Getting PHP sessions to work on AWS Elastic Beanstalk
I recently used Amazon Elastic Beanstalk to deploy a PHP web app that used
$_SESSION. Initially, things did not work. My logs filled up with errors caused by
session_start(), indicating that the session data could not be written to disk. Permission denied. The messages all looked like this:
PHP Warning: Unknown: open(/var/lib/php/session/sess_34etf1ace3tk2vkd7ho8i93uq4, O_RDWR) failed: Permission denied (13) in Unknown on line 0
I found an ancient issue on the AWS forums, but no fix was offered.
The solution to the problem is fairly simple: The Elastic Beanstalk PHP image is misconfigured. It does not write session data to the correct location. The setting needs to be changed. Fortunately, this can be done at runtime.
Typically, session data is written to the temp directory. So on PHP, all we have to do is this:
<?php $dir = sys_get_temp_dir(); session_save_path($dir); ?>
This should occur as early in your app's startup as possible, since it must be executed before