【阿里云】PHP设置session多级路径并定期自动清理

2014-05-03 09:44:10  雅事达网络 我有话说(184人参与)

一、修改 php.ini 配置

vi /usr/local/php/etc/php.ini

 

1、路径和目录深度:

session.save_path = "3;/tmp/session"

 

根目录与深度 3; 代表目录 /tmp/session/1/2/3/ 下保存文件的深度, 如 /tmp/session/1/2/3/sess_id, /tmp/session/a/b/c/sess_id

该目录需要手动创建,必须保留两边的双引号。

 

2、设置 SESSION 最大有效时间, 单位 秒, 最大值 65535

session.gc_maxlifetime = 64800

 

3、设置 SESSIONID 加密级别

session.hash_bits_per_character = 6

 

二、手动生成目录

cd /usr/local/php/include/php/ext/session/

vi mod_files.sh

加入下面的 shell 代码:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#! /bin/sh
# NAME
#      mod_files.sh  - Update of the php-source/ext/session/mod_files.sh
#
# SYNOPSIS
#      mod_files.sh basedir depth [numberofsubdirs]
#
# DESCRIPTION
#      this script creates the directories tree used by php to store the session files
#      (see php.ini - 'session.save_path' option)
#
#      Example: if you want php to store the session files in a directory tree
#      of 3 levels of depth containing 32 directories in each directory,
#      first, put the setting bellow in the php.ini file:
#
#      session.save_path = "3;/tmp/session"
#
#      Now create the basedir directory: 'mkdir /tmp/session'
#
#      Then, call this scrip with the following arguments:
#
#      ./mod_files.sh /tmp/session 3
                
if test "$2" = ""; then
  echo "usage: $0 basedir depth [numberofsubdirs]"
  exit 1
fi
                
if test "$2" = "0"; then
  exit 0
fi
                
hash_chars="0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - ,"
                
for i in $hash_chars; do
  newpath="$1/$i"
  mkdir -p $newpath || exit 1
  sh $0 $newpath `expr $2 - 1`
done

 

昨天发表的文章有个大bug导致目录生成不完整,这是修改后的版本了,今天有用户登陆不了账号才发现,3级目录貌似将需要生成 64*64*64 = 262144 个目录总共,需要等好一段时间的

 

添加文件的执行权限:

chmod +x ./mod_files.sh

 

建立 3 级深度目录, 每级 64 个 以  0-9a-zA-Z,-  字符命名的目录

mkdir /tmp/session

> bash ./mod_files.sh /tmp/session 3 64

请耐心等待一段时间,根据指定的目录深度,时间长度不一样,例如 3级目录将需要生成 262144 个文件夹,估计需要10分钟左右吧

修改目录权限

chmod -R 777 /tmp/session

 

三、测试代码并添加定时任务

查看搜索到的最后修改在 180 分钟前文件总个数

find /tmp/session/ -depth -type f -mmin +180 | wc -l

 

添加定时任务 每天执行一次清理

0 0 * * * find /tmp/session/ -depth -type f -mmin +180 -exec rm -f {} \; &>/dev/null

【特别注意】:如果没有添加自动清理程序,由于自建立的session不会自动过期删除(需手动),所以时间一长会造成:no space left on device 的错误

用:df -i 可以看到存放session的磁盘 inode 达到 100%

 

 

转自:http://snailz.diandian.com/post/2012-11-02/40041019089

 

分享到:

已有37条评论,共184人参与

还没有评论
最新评论刷新
建海666
这里是博客评论区,请登录
32分钟前
果果明赫
这里是博客评论区,请登录
60分钟前