简单力量 - PHP 的二级目录 session 存储

宏哥 发布于 2013/07/13 23:39
阅读 364
收藏 1
PHP

简单实现二级目录来存储 session.

由于linux文件系统很容易缓存, 可以提供很高的性能.

<?php
/**
 * Advance 2 tiers of Directory to save the session.
 */
class Session_Handler{

	public static $sess_save_path = '/tmp';
	/**
	 * Only function to be used to initialize the session handler
	 *
	 * @param String $abs_path, where the session saves
	 *
	 * @return NULL
	 */
	public static function init($abs_path = NULL){
		if($abs_path == NULL){
			self::$sess_save_path = '/tmp';
		}else{
			self::$sess_save_path = $abs_path;
		}

		session_set_save_handler(__CLASS__."::open", __CLASS__."::close", __CLASS__."::read",
			__CLASS__."::write", __CLASS__."::destroy", __CLASS__."::gc");
	}

	/**
	 * Calculate the Session Path on 2 tiers base directory
	 * Could be changed by child
	 *
	 * @param String $id, Session ID
	 *
	 * @return Session Folder Path
	 */
	protected static function getSessionPath($id){
		return self::$sess_save_path."/sess/".$id[0].$id[1].'/'.$id[2].$id[3];
	}

	protected static function getSessionFile($id,$abs_path = NULL){
		if($abs_path == NULL){
			return self::getSessionPath($id).'/'.$id;
		}else{
			return $abs_path.'/'.$id;
		}
	}

	public static function open($save_path, $session_name)
	{
		return(true);
	}

	public static function close()
	{
		return(true);
	}

	public static function read($id)
	{
		$sess_file = self::getSessionFile($id);
		if(!is_file($sess_file)){
			return False;
		}
		return (string) file_get_contents($sess_file);
	}

	public static function write($id, $sess_data)
	{
		$_path = self::getSessionPath($id);
		if(!is_dir($_path)){
			mkdir($_path,0755,TRUE);
		}
		$sess_file = self::getSessionFile($id,$_path);

		if ($fp = fopen($sess_file, "w")) {
			$return = fwrite($fp, $sess_data);
			fclose($fp);
			return $return;
		} else {
			return(false);
		}

	}

	public static function destroy($id)
	{
		$sess_file = self::getSessionFile($id);
		return(unlink($sess_file));
	}

	public static function gc($maxlifetime)
	{

		foreach (glob(self::$sess_save_path."/*") as $filename) {
			if (filemtime($filename) + $maxlifetime < time()) {
				unlink($filename);
			}
		}
		return true;
	}

}

加载中
0
macophp
macophp

如果只是为了将session分目录,可以在php.ini 里设置即可 session.save_path

返回顶部
顶部