Removing old session data form MySQL database

PHP Web applications that use sessions can save data to session files and/or to a database. Session data typically has an expiration timestamp. When session data is saved to a database, the session data is not automatically removed from the database when the expriation time is exceeded. What are some ways to remove this stale information?

Here are a few suggestions for the removal of this stale data:

  • use a cron (unix) or scheduler (windows) to execute SQL to remove the rows
  • use a function that can be accessed manually which executes the SQL to remove the rows
  • when the sessions are initiated, have SQL code be automatically executed to delete the code
DELETE FROM session WHERE expiry < unix_timestamp();

Useful other functions for session expiry timestamp(s):


converts the expiry to MySQL datetime timestamp


MySQL UNIX timestamp in number of epoch seconds


MySQL functions that show current datetime using a UNIX timestamp