Var lib php session cleanup

cleanup php session files

On my website I use PHP sessions. Session information is stored in files in my ./session path. After a few months I discovered that these session files are never deleted, by now there are 145.000 of them in this directory.

How should these be cleaned up? Do I have to do it programmatically, or is ther a setting I can use somewhere that would have this cleanup happen automatically?

EDIT forgot to mention: This site runs at a provider, so I don’t have access to a command line. I do have ftp-access, but the session files belong to another user (the one the webserver proces runs I guess) From the first answers I got I think it’s not just a setting on the server or PHP, so I guess I’ll have to implement something for it in PHP, and call that periodically from a browser (maybe from a cron job running on my own machine at home)

Php Solutions

Solution 1 — Php

There you’ll find these variables:

These control the garbage collector (GC) probability of running with each page request.

You could set those with ini_set() at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.

Solution 2 — Php

Debian/Ubuntu handles this with a cronjob defined in /etc/cron.d/php5

# /etc/cron.d/php5: crontab fragment for php5 # This purges session files older than X, where X is defined in seconds # as the largest value of session.gc_maxlifetime from all your php.ini # files, or 24 minutes if not defined. See /usr/lib/php5/maxlifetime # Look for and purge old sessions every 30 minutes 09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm 

The maxlifetime script simply returns the number of minutes a session should be kept alive by checking php.ini, it looks like this

#!/bin/sh -e max=1440 for ini in /etc/php5/*/php.ini; do cur=$(sed -n -e 's/^[[:space:]]*session.gc_maxlifetime[[:space:]]*=[[:space:]]*\(9\+\).*$/\1/p' $ini 2>/dev/null || true); [ -z "$cur" ] && cur=0 [ "$cur" -gt "$max" ] && max=$cur done echo $(($max/60)) exit 0 

Solution 3 — Php

In case someone want’s to do this with a cronjob, please keep in mind that this:

find .session/ -atime +7 -exec rm <> \; 

is really slow, when having a lot of files.

Consider using this instead:

find .session/ -atime +7 | xargs -r rm 

In Case you have spaces in you file names use this:

find .session/ -atime +7 -print0 | xargs -0 -r rm 

xargs will fill up the commandline with files to be deleted, then run the rm command a lot lesser than -exec rm <> \; , which will call the rm command for each file.

Читайте также:  Блочная верстка в HTML5

Solution 4 — Php

cd to sessions directory and then:

  1. View sessions older than 40 min: find . -amin +40 -exec stat -c «%n %y» <> \;
  2. Remove sessions older than 40 min: find . -amin +40 -exec rm <> \;

Solution 5 — Php

Use cron with find to delete files older than given threshold. For example to delete files that haven’t been accessed for at least a week.

find .session/ -atime +7 -exec rm <> \; 

Solution 6 — Php

You can create script /etc/cron.hourly/php and put there:

#!/bin/bash max=24 tmpdir=/tmp nice find $ -type f -name 'sess_*' -mmin +$ -delete 

Then make the script executable (chmod +x).

Now every hour will be deleted all session files with data modified more than 24 minutes ago.

Solution 7 — Php

# Every 30 minutes, not on the hour # Grabs maxlifetime directly from \`php -i\` # doesn't care if /var/lib/php5 exists, errs go to /dev/null 09,39 * * * * find /var/lib/php5/ -type f -cmin +$(echo "\`php -i|grep -i session.gc_maxlifetime|cut -d' ' -f3\` / 60" | bc) -exec rm -f <> \\; >/dev/null 2>&1 

The Breakdown: Only files: find /var/lib/php5/ -type f
Older than minutes: -cmin
Get php settings: $(echo «`php -i|grep -i session.gc_maxlifetime
Do the math: |cut -d’ ‘ -f3` / 60″ | bc)
RM matching files: -exec rm -f <> \;

Solution 8 — Php

My best guess would be that you are on a shared server and the session files are mixed along all users so you can’t, nor you should, delete them. What you can do, if you are worried about scaling and/or your users session privacy, is to move sessions to the database.

Start writing that Cookie to the database and you’ve got a long way towards scaling you app across multiple servers when time is due.

Apart from that I would not worry much with the 145.000 files.

Solution 9 — Php

39 20 * * * root [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm 

Источник

Can’t delete php sessions

I have read dozens of posts on his subject, yet cannot find a solution that works for me. I have a user account. PHP sessions for that account are stored in /home/user/tmp Apache start tossing errors that i can’t open sessions because the device is full. df and df -i both show me that the device has plenty of space. So I look to he /home/user/tmp directory. It shows the size of the directory is 901MB. I wan to delete the session files from the directory. I have tried rm -rf /home/user/tmp/sess_* I let his run for over an hour then used cntr+C to kill the command. The directory still says 901 MB. I have rebooted the system, the directory still shows at 901MB. I have tried find /home/*/tmp -type f -name ‘sess_*’ -ctime +5 -delete Just like with rm -rf I let the command run for over an hour and killed it. The directory still shows 901MB. I am issuing these commands as root user. I am using ubuntu 16.04. This is a server so only command line options will work. What can I do to remove these session files?

3 Answers 3

Often you can’t delete session files even with command like sudo rm -rf /var/lib/php/sessions/* because a path name expansion occurs BEFORE the sudo (https://serverfault.com/a/851261/591003).

You can try another command like sudo sh -c «rm -rf /var/lib/php/sessions/*» but if you have tons of files you’ll get an answer that rm: Argument list too long because the list of session files is usually very huge (up to millions of files).

I propose a really simple way:

  1. Create a new folder sessions_new: mkdir /var/lib/php/sessions_new
  2. Set the same permissions as for old sessions directory: sudo chmod —reference=sessions sessions_new
  3. Do the same with ownership: sudo chown —reference=sessions sessions_new
  4. Kill it! sudo rm -rf /var/lib/php/sessions
  5. You don’t need to wait a result for a long time. You can check it immediately in a new terminal window by sudo find /var/lib/php/sessions/. -type f|wc -l . This command counts the number of files inside your sessions folder. Run it two times. If the second time you run the command, you get a lower number than the first time, then the process is going in the right direction.
  6. Wait for a long time 😛
  7. When process has finished just rename the session_new directory: mv /var/lib/php/sessions_new /var/lib/php/sessions

Источник

Удаление устаревших PHP сессий в Debian

Удаление устаревших PHP сессий в Debian

Ни для кого не секрет, что в PHP существует так называемый «garbage collector» — сборщик мусора для удаления устаревших сессионных данных. По умолчанию, garbage collector подчищает только те сессии, которые не были использваны в течении предыдущих 24х минут (время задается в директиве session.gc_maxlifetime файла конфигурации php.ini), а сами сессии храняться в файлах. Так же garbage collector запускается при старте механизма сессий (т. е.session_start()), но не каждый раз, а с некой периодичностью, определяемой соотношением величин session.gc_probability / session.gc_divisor — это «вероятность» запуска сборщика мусора. И вообщем-то казалось бы все довольно очевидно и кроссплатформено, но … оказывается что в Debian-е все устроено не совсем так, как у всех

Cтолкнулся я с этим совсем недавно. На одном из проектов на сервере под Debian-ом возникла небольшая проблемка — сессии наотрез отказывались удаляться. Оказывается причиной всему была нестандартная реализация механизма GC в PHP под Debian-ом. Исходя из соображений безопасности стандартный GC был вообще полностью отключен, а вместо него отрабатывал вот такой вот CRON-овский таск: /etc/cron.d/php5 (собственно, проблема заключалась в том, что этот таск был по каким-то неведомым для меня причинам закомменчен)

# /etc/cron.d/php5: crontab fragment for php5 # This purges session files older than X, where X is defined in seconds # as the largest value of session.gc_maxlifetime from all your php.ini # files, or 24 minutes if not defined. See /usr/lib/php5/maxlifetime # Look for and purge old sessions every 30 minutes 09,39 * * * * root [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -n 200 -r -0 rm

Как видно из листинга выше, таск выполняется каждые 9 и 39 минут, при помощи вспомогательного bash скрипта /usr/lib/php5/maxlifetime парсит php.ini на наличие директивы session.gc_maxlifetime, и затем просто тупо удаляет все найденные «устаревшие» файлы из директории /var/lib/php5. Скрипт /usr/lib/php5/maxlifetime:

#!/bin/sh -e max=1440 for ini in /etc/php5/*/php.ini; do cur=$(sed -n -e 's/^[[:space:]]*session.gc_maxlifetime[[:space:]]*=[[:space:]]*\(7\+\).*$/\1/p' $ini 2>/dev/null || true); [ -z "$cur" ] && cur=0 [ "$cur" -gt "$max" ] && max=$cur done echo $(($max/60)) exit 0

Один из минусов данной реализации: жестко заданная директория /var/lib/php5. Конечно же, эту директорию несложно поменять, но для этого надо лезть в кроновский таск, что довольно неочевидно. Жестко заданны 9 и 39 минут (хотя в 90% случаев заданного интервала вполне будет хватать). А ещё к минусам можно отнести поиск директивы session.gc_maxlifetime исключительно в /etc/php5/*/php.ini, хотя поидее она может быть задана в файлах /etc/php5/*/conf.d/*.ini . Кстати говоря, оказывается эта бага описана на багтрекере Debian: #508007. Само собой разумеется, это упущение тоже не так уж сложно поправить, но тем не менее для этого необходимо немного пошевелить мозгами, попереписывать bash-скрипты… У данного подхода имеются и свои плюсы: один из них — безопасность (ага, ради чего все и затевалось), а второй — скрипт удаления сессий не связан с интерпритаром, что делает его менее «нагруженным».

Отмечу ещё раз — данный механизм относится ТОЛЬКО к реализации стандартного GC, основанного на хранении данных сессии в файлах. При переопределении механизма сохранения сессий в БД или в memcache, переопределенный GC (например, через функцию session_set_save_handler()) будет отрабатывать так, как и положено согласно документации PHP.

P.S. Аналогичный механизм работы GC присутствует и в дистрибутиве Ubuntu. Оно и ясно — производная от Debian-а. Про остальные дистрибутивы (типо Dreamlinux), основанные на Debian, ничего сказать не могу, но скорее всего все это дело там реализовано аналогичным образом.

Источник

Оцените статью