微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php将session保存到数据库的简单示例

PHP中将session保存到数据库代码感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!
我们可以使用session_set_save_handler()来注册连接数据的函数。下面是完整的演示代码

/**
 * PHP中将session保存到数据库代码
 *
 * @param 
 * @arrange 512-笔记网: 512Pic.com
 **/
// 'sessions' table schema
// create table sessions (
//   session_id char(32) not null,//   session_data text not null,//   session_expiration int(11) unsigned not null,//   primary key (session_id));
//
include_once 'DB.PHP';
// Global Variables
$dbh = NULL;
function on_session_start ($save_path,$session_name) {
	global $dbh;
	$dbh = DB::connect('MysqL://user:secret@localhost/SITE_SESSIONS',true);
	if (DB::isError($dbh)) {
		die(sprintf('Error [%d]: %s',$dbh->getCode(),$dbh->getMessage()));
	}
}
function on_session_end ()
{
   // nothing needs to be done in this function
   // since we used persistent connection.
}
function on_session_read ($key)
{
	global $dbh;
	$stmt = select session_data from sessions;
	$stmt .=  where session_id = '$key';
	$stmt .=  and session_expiration > Now();
	$sth = $dbh->query($sth);
	$row = $sth->fetchRow(DB_FETCHMODE_ASSOC);
	return $row['session_data'];
}
function on_session_write ($key,$val)
{
	global $dbh;
	$val = addslashes($val);
	$insert_stmt = insert into sessions values('$key','$val',Now() + 3600);
	$update_stmt = update sessions set session_data = '$val',;
	$update_stmt .= session_expiration = Now() + 3600 ;
	$update_stmt .= where session_id = '$key';
	// First we try to insert,if that doesn't succeed,it means
	// session is already in the table and we try to update
	if (DB::isError($dbh->query($insert_stmt)))
		$dbh->query($update_stmt);
}
function on_session_destroy ($key)
{
	global $dbh;
   $stmt = delete from sessions where session_id = '$key';
   $dbh->query($stmt);
}
function on_session_gc ($max_lifetime)
{
	global $dbh;
	// In this example,we don't use $max_lifetime parameter
	// We simply delete all sessions that have expired
	$stmt = delete from sessions where session_expiration < Now();
	$dbh->query($stmt);
}
session_start ();
// Register the $counter variable as part
// of the session
session_register (counter);
// Set the save handlers
session_set_save_handler (on_session_start,on_session_end,on_session_read,on_session_write,on_session_destroy,on_session_gc);
// Let's see what it does
$counter++;
print $counter;
session_destroy();

/***   来自编程之家 jb51.cc(jb51.cc)   ***/

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐