zl程序教程

您现在的位置是:首页 >  后端

当前栏目

php自定义session示例分享

PHP 示例 分享 自定义 session
2023-06-13 09:15:25 时间

下面为session类的代码

复制代码代码如下:

<?php
classsession
{
 staticfunctioninit()
 {
  session_set_save_handler(
    array("session","open"),
    array("session","close"),
    array("session","read"),
    array("session","write"),
    array("session","destroy"),
    array("session","gc")
  );
 }

 staticfunctionopen($save_path,$session_name)
 {
  echo"sessionopening!<br>";
  /*global$db,$REMOTE_ADDR;
  $rs=$db->Execute("select*fromSessionswhereSessionID="".session_id().""");
  $arry=$rs->FetchRow();
  if($rs&&$arry)
  {
  $db->Execute("updateSessionssetSessionLast=NOW()whereSessionID="".session_id().""");
  }
  else
  {
  $query="insertintoSessionssetSessionID="".session_id()."",SessionName="$REMOTE_ADDR",SessionLast="NOW()"";
  //echo$query;
  $db->Execute($query);
  }*/
  returntrue;
 }
 staticfunctionclose()
 {
  return(true);
 }

 staticfunctionread($id)
 {
  echo"sessionreadingnow!<br>";
  global$db;
  returntrue;
  $timenow=strftime("%Y-%m-%d%H:%M:%S",time());
  $query="selectSessionDatafromSessionswhereSessionID="$id"andSessionLast>"$timenow"";
  $rs=$db->Execute($query);
  if(list($SessionData)=$rs->FetchRow())
  {
   //echo$SessionData;
   return$SessionData;
  }
  else
  {
   returnfalse;
  }
 }

 staticfunctionwrite($id,$sess_data)
 {
  echo"sessionwritingnow!<br>";
  global$db;
  $rs=$db->Execute("selectSessionIDfromSessionswhereSessionID="$id"");
  $num=$rs->RecordCount();
  $unix_time=time()+MY_SESS_TIME;
  //echoMY_SESS_TIME;
  $dateleft=strftime("%Y-%m-%d%H:%M:%S",$unix_time);
  if($num<=0)
  {
   $sql="insertintoSessionssetSessionData="$sess_data",SessionName="".$_SERVER["REMOTE_ADDR"]."",SessionLast="$dateleft",SessionID="".session_id().""";
  }
  else
  {
   $sql="updateSessionssetSessionData="$sess_data",SessionName="".$_SERVER["REMOTE_ADDR"]."",SessionLast="$dateleft"whereSessionID="$id"";
  }
  $db->Execute($sql);
 }

 staticfunctiondestroy($id)
 {
  echo"sessiondestroyingnow!<br>";
  global$db;
  $sql="DELETEFROMSessionsWHERE`SessionID`="$id"";
  $rs=$db->Execute($sql);
  return$rs;
  //$sess_file="$sess_save_path/sess_$id";
  //return(@unlink($sess_file));
 }

 /*********************************************
 *WARNING-Youwillneedtoimplementsome*
 *sortofgarbagecollectionroutinehere.*
 *********************************************/
 staticfunctiongc($maxlifetime)
 {
  echo"sessionmaxlifetimenow!<br>";
  global$db;
  $timenow=strftime("%Y-%m-%d%H:%M:%S",time());
  $sql="DELETEFROM`$table_sessions`WHERE`SessionLast`<"$timenow"";
  return$sess_db->Execute($sql);
  //echo"nowgc!<br>";
  returntrue;
 }
 //proceedtousesessionsnormally
}

使用方法

复制代码代码如下:

include("session.class.php");
session::init();
session_start();
define("MY_SESS_TIME",3600);//SESSION生存时长
$_SESSION["test"]="abcdef";