PHP设置session定期自动清理的例子

下文来为各位介绍PHP设置session定期自动清理的例子了,因为session默认是15分钟自动把变量给清除内存了,但有一些时间并不生效了,下面我们就来看看.

配置完成php后,默认php会将session生成到/tmp目录下,导致/tmp目录文件很多,因此需要对session进行定期的清理.

修改php.ini:

  1. [root@hz scripts]# grep "session.save_path = " /usr/local/php/lib/php.ini
  2. ; session.save_path = "N;/path"
  3. ; session.save_path = "N;MODE;/path"
  4. ;session.save_path = "/tmp"
  5. session.save_path = "2;/tmp/session"
  6. [root@hz ~]# cat /byrd/script/Cleartmpsen.sh
  7. #!/bin/bash
  8. # Version:1.0
  9. # Author:Byrd
  10. # Site:www.t4x.org
  11. # Contact:root#t4x.org
  12. # This is script will clear php session before 3 hours.
  13. i="0 1 2 3 4 5 6 7 8 9 a b c d e f"
  14. for byrd in $i;
  15. do
  16. for x in $i;
  17. do
  18. mkdir -p /tmp/session/$byrd/$x;
  19. done;
  20. done
  21. chown -R bywww:bywww /tmp/session
  22. chmod -R 1777 /tmp/session
  23. find /tmp/session -amin +180 -exec rm -rf {} \;
  24. if [ `grep 'session.save_path =' /usr/local/php/lib/php.ini | wc -l` -eq 3 ];then
  25. sed -i 's#;session.save_path = "/tmp"#;session.save_path = "/tmp"\nsession.save_path = "2;/tmp/session"#g' /usr/local/php/lib/php.ini
  26. else
  27. exit 1
  28. fi
  29. 定时任务:
  30. [root@hz scripts]# echo '#This is a config php session BY:BYRD AT:2014-03-31' >>/var/spool/cron/root
  31. [root@hz scripts]# echo '0 3 * * 0 /bin/bash /byrd/scripts/spehspsion.sh >/dev/null 2>&1' >>/var/spool/cron/root

备注:因为此配置修改了php.ini因此需要重新启动php进程.