Ubuntu 16.04 PHP Garbage Collection is Garbage

I recently upgraded an Ubuntu 14.04 Server to 16.04. I immediately noticed the root mail being spammed with error e-mails as below:

From: Cron Daemon [mailto:root@jack]
Sent: Wednesday, March 13, 2019 4:09 PM
To: root@jack
Subject: Cron <root@jack> [ -x /usr/lib/php/sessionclean ] && /usr/lib/php/sessionclean

/usr/lib/php/sessionclean: 37: /usr/lib/php/sessionclean: arithmetic expression: expecting primary: “/60”

Debian/Ubuntu has a peculiar method of cleaning up stale sessions via a script that runs every 30 minutes by a cron job located at /etc/cron.d/php5

On any web server running PHP, it’s imperative that old PHP sessions get removed. If not, eventually you’ll have hundreds of thousands of session files. At some point, the server will run out of inodes and come to a screeching halt. I gave good effort trying to get the built-in sessionclean to work, but came up with a better solution for my needs instead. I run the shell script below as a daily cron job. It deletes all sessions over 12 hours.

Before running something like this on your server, you should probably uncomment the commented lines, and comment the line “find -cmin +720 | xargs rm”. This way, you’ll get a listing of all files that would be deleted without actually deleting them. You might also want to redirect the output to a file so you can review it, as in “find -cmin +720 | cat >> results.txt”.

#!/bin/sh

cd /var/lib/php/sessions
echo "Number of sessions prior to pruning:"
ls -l /var/lib/php/sessions | wc -l
echo " "
#echo "These sessions will be deleted:"
#find -cmin +720 | cat
#echo " "
echo "Deleting old sessions..."
find -cmin +720 | xargs rm
echo " "
echo "Number of sessions after pruning:"
ls -l /var/lib/php/sessions | wc -l