PHP設置session多級路徑並定期自動清理
一、修改 php.ini 配置
vi /usr/local/php/etc/php.ini
1、路徑和目錄深度:
session.save_path = "3;/tmp/session"
根目錄與深度 3; 代表目錄 /tmp/sess/1/2/3/ 下保存文件的深度, 如 /tmp/sess/1/2/3/sess_id, /tmp/sess/a/b/c/sess_id
該目錄需要手動創建,必須保留兩邊的雙引號。
2、設置 SESSION 最大有效時間, 單位 秒, 最大值 65535
session.gc_maxlifetime = 10800
3、設置 SESSIONID 加密級別
session.hash_bits_per_character = 6
二、手動生成目錄
cd /usr/local/php/include/php/ext/session/
vi mod_files.sh
加入下麵的 shell 代碼:
#! /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
./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
=================================================================================
PS:2014/02/27 01:18
我以前這麼處理過一段時間,但遇到過無數問題,非常鬱悶,甚至差點導致文件係統崩潰,阿裏雲服務器的硬盤感覺確實不怎麼滴,服務器為此經常超載,出現很多幽靈 session 文件,root 權限都刪除不掉,後來放棄使用硬盤存儲了,采用 memcache 內存緩存了,這些煩人的問題都沒了
最後更新:2017-04-03 12:55:18