Update cookies preferences

Clearing Thousands of old Magento Cache files

I thought I’d share some tips to dealing with the issue of the Magento 1.9 cache folder containing too many files.
After investigating a new site I found over 300,000 files present in the var/session folder.

This happens due to the php’s config session.gc_maxlifetime value and similar config being incorrectly set, which that causes PHP’s garbage collection to not running correctly.

Common advice

Most advice to clear files older then 30 days for example will give a command like this.

find ./session -type f -name 'sess_*' -mtime +30 -exec rm { } \;

But the problem is when the session folder contains too many files this won’t work.

To find out how many files are present run the following command inside the session folder.

ls | wc -l

If you have tens of thousands of files+ then you have a problem.

This will cause an error and that line above to not delete the files due to the number of args passed to the rm command, so what are the options

Delete the session folder directly? 🙁

If you have no site users anymore, or don’t care about anything people have in their baskets then this is an option (VERY BAD OPTION)

A better solution

2. A better solution is to make use of the ls -c | head -n command,

This will return only a subtest of results, these can then be run multiple times effectively paginating the args to the rm command.

So the following will remove the first 5000 oldest files, inside the session folder

cd ./session

ls -c | head -n 5000 | xargs -d '\n' rm

Then running count again should show 5000 less files.

ls | wc -l

Once you’ve cleared the older files down to a manageable level make sure you configure Garbage collection correctly, there’s a great article here that will help


If you enjoyed this article, read our other Learn articles to see more from our Magento developers or browse the site to see what else we do with Adobe Commerce, PunchOut Catalog and more.

Need a hand or want to consult with our developers on your latest project?



Ready to start your next project?

See how we can help you accelerate your business