# php_session_diy **Repository Path**: yiranteam/php_session_diy ## Basic Information - **Project Name**: php_session_diy - **Description**: 重写session - **Primary Language**: PHP - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2017-04-27 - **Last Updated**: 2021-10-01 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #php_session_diy cookieInit(); $this->sessionInit(); $this->gc(); } //获取/设置session方法 public function val($key = '',$val = ''){ if(empty($key)) return; if($val === ''){ return isset($this->sessionval[$key])?$this->sessionval[$key]:''; }else{ if(empty($val)) return; $this->setSession($key,$val); } } //cookie初始化 protected function cookieInit(){ if(empty($_COOKIE['PHP_SESSID'])){ //key加了下划线,为了防止与自带session冲突 $this->cookieval = md5(microtime().rand(0,100000)); }else{ $this->cookieval = $_COOKIE['PHP_SESSID']; } setcookie('PHP_SESSID',$this->cookieval,time()+$this->lifetime); } //session系统初始化 protected function sessionInit(){ if(!empty($this->sessionval)) return; $filename = 'session'.$this->cookieval.'.txt'; $this->filedir = rtrim(str_replace('\\','/',__DIR__),'/').'/sessionfile'; if(!is_dir($this->filedir)) mkdir($this->filedir); $this->filepath = $this->filedir.'/'.$filename; if(!file_exists($this->filepath) || time() - filemtime($this->filepath) > $this->lifetime){ $json = ''; $content = ''; }else{ $json = file_get_contents($this->filepath); $content = $json?json_decode($json,1):''; } $this->sessionval = is_array($content)?$content:array(); file_put_contents($this->filepath,$json); } //设置session值 protected function setSession($key,$val){ $this->sessionval[$key] = $val; file_put_contents($this->filepath,json_encode($this->sessionval,JSON_UNESCAPED_UNICODE)); } //session文件垃圾回收 protected function gc(){ $rand = rand(0,1000); if($rand < $this->gcrate){ foreach (scandir($this->filedir) as $value) { if($value != '.' && $value != '..'){ $path = $this->filedir.'/'.$value; if(time() - filemtime($path) > $this->lifetime){ //echo $path; unlink($path); } } } } } }