Skip to content
Advertisement

Are PHP session writes atomic?

As PHP session handler was somehow flawed in the past, we developed a homemade session handler years ago. But it seems that current versions of PHP are well developed and flaws are gone, and we decided to use PHP’s default session handler (as it is much faster than our handler which uses dbms to save session data – which sometimes have to read/write megabytes of data).

The only question which we couldn’t find an answer for is if PHP’s default session handler is atomic or not?

We know that the session files are locked so are prone to race condition, but what about atomicity? What if megabytes of data are going to be saved in a session file, and some errors happens in the middle (power outage, crash or disk failure for example). What happens now? are session data corrupted now? Or old data are still in place?

We don’t have a C programmer in our team, but I looked in PHP’s source code and I found the line that is responsible for writing sessions to files, but I was unable to find s_write()’s source code’s file.

ret = PS(mod)->s_write(&PS(mod_data), PS(id), val, PS(gc_maxlifetime));

Here is the source file (line 487): https://github.com/php/php-src/blob/master/ext/session/session.c

Advertisement

Answer

After some digging in the source, I’ve found the function that writes the data to the disk.

3 functions can be used by ps_files_write to write data:

  • _write, on Win32
  • prwite, which seems to be a UNIX function, I don’t know much about that one honestly.
  • write, the basic C system call.

As per the links above, all of them are “atomic” in the way that they do not flush the write buffer if an error has been encountered (not enough disk space, unauthorized access, locked file, etc.).

ps_files_write returns an status value (either SUCCESS or FAILURE) which is then later on checked in php_session_save_current_state to return an ERROR to the PHP script.

So yes, generally you can consider session writes to be “atomic”, even though on some cases you will not be able to guarantee it (if the power is cut suddenly, the system stops within microseconds, so nothing can be saved…).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement