自定义方式保存session到文件

/**
 * 自定义方式保存session到文件
 * 使用session_set_save_handler 函数
 * php.ini 设置
 * 默认为session.save_handler = files,必须将其修改为session.save_handler = user,即变为用户自定义方式。
 */
//在运行session_start()会执行
function open($save_path, $session_name) {//启动回话
	global $sess_save_path;
	$sess_save_path=$save_path;
	return true;
}

//sessin_writr_close() session_destroy()
function close() {
	return true;
}

//session_start() ,$_SESSION
function read($id) {//读取session
	global $sess_save_path;
	$sess_file=$sess_save_path."/glf_".$id;
	if (file_exists($sess_file)){
	  return (string)file_get_contents($sess_file);
	}else {
		return false;
	}
}

//结束时和sessin_writr_close()强制提交数据是$_SESSION[]="aaa";
function write($id ,$sess_data) {
	global $sess_save_path;
	$sess_file=$sess_save_path."/glf_".$id;
	
	if ($fp=fopen($sess_file, "w")){
		$return=fwrite($fp, $sess_data);
		fclose($fp);
		return $return;
	}else {
		return false;
	}
}

//session_destroy()
function destroy($id) {
	global $sess_save_path;
	$sess_file=$sess_save_path."/glf_".$id;
	return unlink($sess_file);
}

//session.gc_probability和 session.gc_divisor值决定的,open(), read() session_start也会执行gc
function gc($maxlifetime) {
	global $sess_save_path;
	
	foreach (glob($sess_save_path."/glf_*") as $filename){
		if (filemtime($filename)+$maxlifetime < time()){
			unlink($filename);
		}
	}
	return true;
}

session_set_save_handler("open", "close", "read", "write", "destroy", "gc");

session_start();


调用文件1 file1.php

//原始方式
/*
session_start();

$_SESSION["islogin3"] = 1;
$_SESSION["username"] = "admin";
$_SESSION["uid"] = 333;

echo session_name().'='.session_id()."
"; */ //session_set_save_handler 方式 include 'session.php'; $_SESSION["islogin3"] = 1; $_SESSION["username"] = "admin"; $_SESSION["uid"] = 333; echo session_name().'='.session_id()."
";


调用文件2 file2.php

//原始方式
/*
session_start();

print_r($_SESSION);
echo "
"; echo session_name().'='.session_id()."
"; */ //session_set_save_handler 方式 include 'session.php'; print_r($_SESSION); echo "
"; echo session_name().'='.session_id()."
";


调用文件3 file3.php

//原始方式
/*
session_start();

$_SESSION = array();
if (isset($_COOKIE[session_name()])){
	setcookie(session_name(), '' , time()-100, '/');
}
session_destroy();

echo session_name().'='.session_id()."
"; */ //session_set_save_handler 方式 include 'session.php'; $_SESSION = array(); if (isset($_COOKIE[session_name()])){ setcookie(session_name(), '' , time()-100, '/'); } session_destroy(); echo session_name().'='.session_id()."
";

你可能感兴趣的:(php)