Magento Performance Boost: Cleanup Old Session Files

If left unchecked, Magento session files can grow out of control and have a negative impact on your sites performance (aswell as taking up storage space). This article explains how to make sure old session files are removed automatically.

Magento stores it’s session files in var/session and I’ve seen too many Magento installations where the size of this directory has grown into the gigabytes. A quick browse of this directory should tell you whether you have a problem or not.

PHP has it’s own ‘garbage collection’ process for deleting old session files, but it’s disabled in Debian “due to the strict permissions on /var/lib/php5”
So, if you are using Debian then you’ll need to setup a simple cron script to do this garbage collection for you.

For this example, let’s say the path to your Magento installation is /path/to/magento and we want to delete session files over a week old.

  1. Create a new file /path/to/magento/session_cleanup.sh
    vi /path/to/magento/session_cleanup.sh
  2. Add the following 2 lines to the file
    #!/bin/sh
    find /path/to/magento/var/session -name 'sess_*' -type f -mtime +7 -exec rm {} \;
  3. Make sure the file is executable
    chmod u+x /path/to/magento/session_cleanup.sh
  4. Now add it to your crontab
    crontab -e

    and set it to run every day, let’s say at 3am

    0 3 * * *  /bin/sh /path/to/magento/session_cleanup.sh

And we’re done.

4 Responses to “Magento Performance Boost: Cleanup Old Session Files”

  1. After 6 month without manual cleaning a had with a good visited customer shop 12,3 MB in this folder. Now with the script everything should work fine. I wondered, why file-system-check needs so much time. But now the shop should work quicker…

  2. Thanx a lot for this tip, it’s really weird that magento’s package doesn’t inlclude that kind of features by default

  3. Im getting bash: /usr/bin/find: Argument list too long

    The path is /var/www/magento/var/session/*

    If I use /var/www/magento/var/* then it works fine… it obviously has a max length on the folder path

    • Hi Christian, thanks for your comment.
      You don’t need the /* on your path as you are specifying a directory..
      i.e. try your path as: /var/www/magento/var/session