將session儲存到資料庫中

巴扎黑
發布: 2016-11-10 13:43:16
原創
1003 人瀏覽過

Sql語句程式碼  

CREATE TABLE sessions (  
  id CHAR(32) NOT NULL,  
  data TEXT,  
  last_accessed TIMESTAMP NOT NULL,  
  PRIMARY KEY (id)  
);
登入後複製

自訂會話處理程式碼  

<?php  
/**  
 * Created by PhpStorm.  
 * User: michaeldu  
 * Date: 15/7/14  
 * Time: 下午2:57  
 */  
$sdbc = NULL;  
  
function open_session() {  
    global $sdbc;  
    $sdbc = mysqli_connect(&#39;192.168.31.172&#39;, &#39;root&#39;, &#39;root&#39;, &#39;phpadvanced&#39;);  
    return true;  
}  
  
function close_session() {  
    global $sdbc;  
    return mysqli_close($sdbc);  
}  
  
function read_session($sid) {  
    global $sdbc;  
    $q = sprintf(&#39;SELECT data FROM sessions WHERE  id="%s"&#39;, mysqli_real_escape_string($sdbc, $sid));  
    $r = mysqli_query($sdbc, $q);  
  
    if (mysqli_num_rows($r) == 1) {  
        list($data) = mysqli_fetch_array($r, MYSQLI_NUM);  
        return $data;  
    } else {  
        return &#39;&#39;;  
    }  
}  
  
function write_session($sid, $data) {  
    global $sdbc;  
  
    $q = sprintf(&#39;REPLACE INTO sessions (id, data) VALUES ("%s", "%s")&#39;, mysqli_real_escape_string($sdbc, $sid), mysqli_real_escape_string($sdbc, $data));  
    $r = mysqli_query($sdbc, $q);  
    return true;  
}  
  
function destroy_session($sid) {  
    global $sdbc;  
    $q = sprintf(&#39;DELETE FROM session WHERE id="%s"&#39;, mysqli_real_escape_string($sdbc, $sid));  
    $r = mysqli_query($sdbc, $q);  
  
    $_SESSION = array();  
  
    return true;  
}  
  
function clean_session($expire) {  
    global $sdbc;  
  
    $q = sprintf(&#39;DELETE FROM sessions WHERE DATE_ADD(last_accessed, INTERVAL %d SECOND) < NOW()&#39;, (int)$expire);  
    $r = mysqli_query($sdbc, $q);  
  
    return true;  
}  
  
session_set_save_handler(&#39;open_session&#39;, &#39;close_session&#39;, &#39;read_session&#39;, &#39;write_session&#39;, &#39;destroy_session&#39;, &#39;clean_session&#39;);  
  
session_start();
登入後複製

 

在普通頁面上呼叫程式碼  

  
    
    
    colour_blue  
      
      
      
        
    
<?php  
if(empty($_SESSION)) {  
    $_SESSION[&#39;blah&#39;] = &#39;umlaut&#39;;  
    $_SESSION[&#39;this&#39;] = 3615684.45;  
    $_SESSION[&#39;that&#39;] = &#39;blue&#39;;  
    echo &#39;Session已存储&#39;;  
} else {  
    echo &#39;SESSION已存在, &#39;.print_r($_SESSION, 1).&#39;&#39;;  
}  
  
if(isset($_GET[&#39;logout&#39;])) {  
    session_destroy();  
    echo &#39;会话结束&#39;;  
} else {  
    echo &#39;登出&#39;;  
}  
  
echo &#39;会话数据: &#39;.print_r($_SESSION, 1).&#39;&#39;;  
?>
登入後複製


相關標籤:
sql
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板