CodeIgniter 3.1.5会话缓存文件夹频繁满溢,求自动清理方案
问题:CodeIgniter 3.1.5 会话缓存文件夹快速占满的自动清理方案
环境信息
- 使用框架:CodeIgniter
- 版本:
CI_VERSION = '3.1.5'
当前会话配置(config.php)
/* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_cookie_name' = the name you want for the cookie | 'sess_expiration' = the number of SECONDS you want the session to last. | by default sessions last 7200 seconds (two hours). Set to zero for no expiration. | 'sess_expire_on_close' = Whether to cause the session to expire automatically | when the browser window is closed | 'sess_encrypt_cookie' = Whether to encrypt the cookie | 'sess_use_database' = Whether to save the session data to a database | 'sess_table_name' = The name of the session database table | 'sess_match_ip' = Whether to match the user's IP address when reading the session data | 'sess_match_useragent' = Whether to match the User Agent when reading the session data | 'sess_time_to_update' = how many seconds between CI refreshing Session Information | */ $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 0; $config['sess_expire_on_close'] = TRUE; $config['sess_encrypt_cookie'] = FALSE; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 3000; $config['sess_save_path'] = FCPATH . 'application/cache1/';
问题描述
当前会话文件存储在FCPATH . 'application/cache1/',该文件夹每2天会被占满(900MB-1GB),导致磁盘空间不足、网站无法正常运行,日志已出现相关报错。需要实现自动清理缓存的方案(如Cron任务),同时必须避免修改sess_save_path导致所有用户被迫重新登录。
解决方案
方案1:Cron任务清理过期会话文件(推荐)
CodeIgniter文件型会话的文件名包含过期时间戳,可直接筛选并删除过期文件,不会影响活跃会话。
- 编写Shell清理脚本(如
clean_ci_sessions.sh)
#!/bin/bash # 替换为你的实际会话存储路径 SESSION_PATH="/your/project/path/application/cache1/" # 删除24小时前创建的会话文件,按需调整:-mmin +720 表示删除12小时前的文件 find "$SESSION_PATH" -name "ci_session_*" -type f -mtime +0 -delete
- 给脚本添加执行权限
chmod +x clean_ci_sessions.sh
- 配置Cron每日自动执行
运行crontab -e,添加以下内容(每日凌晨2点执行清理):
0 2 * * * /path/to/your/clean_ci_sessions.sh
方案2:调整CodeIgniter内置清理机制
CodeIgniter 3.x文件会话驱动默认会在会话初始化时清理过期文件,但触发概率较低。可修改配置提高清理频率:
在config.php中添加/修改以下配置:
# 每次会话初始化时触发清理的概率(数值越小,清理越频繁) $config['sess_cleanup_probability'] = 1;
默认值为100(每100次请求触发1次清理),改为1后每次请求都会尝试清理过期文件,无需额外Cron任务,适合无法配置定时任务的环境。
注意事项
- 禁止修改
sess_save_path,否则已存在的会话文件无法被识别,会导致所有用户强制登出。 - 清理时仅针对
ci_session_*格式的文件,避免误删其他缓存内容。 - 使用Cron方案时,确保执行Cron的用户拥有会话文件夹的读写权限。
内容的提问来源于stack exchange,提问作者Misha
相关产品推荐
相关产品推荐

