在共享主机上的数据库中存储会话数据

时间:2014-05-01 01:40:32

标签: php session

我很难搞清楚这一个。请记住,我对PHP比较陌生,所以我希望有人可以帮助我。

我正在尝试将我网站的会话数据存储到我的数据库中的表sessions中。出于安全原因,我这样做是因为我的网站托管在共享服务器上。

我找到了这个脚本,我修改它以使用mysqli。这是我的session.php文件,每个页面都会调用它:

<?php

session_start();

session_set_save_handler('_open', '_close', '_read', '_write', '_destroy', '_clean');

require("constants.php");

function _open() {
    global $_sess_db;

    $_sess_db = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);

    return FALSE;
}

function _close() {
    global $_sess_db;
    return mysqli_close($_sess_db);
}

function _read($id) {
    global $_sess_db;

    $id = mysqli_real_escape_string($_sess_db, $id);

    $sql = "SELECT data FROM sessions WHERE id = '{$id}'";

    if ($result = mysqli_query($_sess_db, $sql)) {
        if (mysqli_num_rows($result)) {
            $record = mysqli_fetch_assoc($result);
            return $record['data'];
        }
    }

    return '';
}

function _write($id, $data) {   
    global $_sess_db;

    $access = time();

    $id = mysqli_real_escape_string($_sess_db, $id);
    $access = mysqli_real_escape_string($_sess_db, $access);
    $data = mysqli_real_escape_string($_sess_db, $data);

    $sql = "REPLACE INTO sessions (id, access, data) VALUES ('{$id}', '{$access}', '{$data}')";

    return mysqli_query($_sess_db, $sql);
}

function _destroy($id) {
    global $_sess_db;

    $id = mysqli_real_escape_string($_sess_db, $id);

    $sql = "DELETE * FROM sessions WHERE id = '{$id}'";

    return mysqli_query($_sess_db, $sql);
}

function _clean($max) {
    global $_sess_db;

    $old = time() - $max;
    $old = mysqli_real_escape_string($_sess_db, $old);

    $sql = "DELETE * FROM sessions WHERE access < '{$old}'";

    return mysqli_query($_sess_db, $sql);
}

这不起作用。会话未写入会话表。任何人都可以帮我看看为什么?提前谢谢!


我将顶部更改为:

<?php

session_set_save_handler('_open', '_close', '_read', '_write', '_destroy', '_clean');
session_start();

function _open() {
    global $_sess_db;
    require("constants.php");
    $_sess_db = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);

    return FALSE;
}

因为我读到需要在session_set_save_handler()之前调用session_start(),但现在它说$_sess_db在所有mysqli_query语句中都为空。

1 个答案:

答案 0 :(得分:0)

它不是重复这个并纠正我选择发布代码的所有问题:http://php.net/session_set_save_handler它包含了处理会话数据的正确设置。它发布者:stalker at ruun dot de更新为使用mysqli

<?php 

/*
Requires:
CREATE TABLE `ws_sessions` ( 
  `session_id` varchar(255) binary NOT NULL default '', 
  `session_expires` int(10) unsigned NOT NULL default '0', 
  `session_data` text, 
  PRIMARY KEY  (`session_id`) 
);

*/

error_reporting( E_ALL );

class session { 
    // session-lifetime 
    var $lifeTime; 
    // mysqli-handle 
    var $dbHandle;

    function open($savePath, $sessName) { 
        echo "Called session->open(savepath, sessname)<br>";
       // get session-lifetime 
       $this->lifeTime = get_cfg_var("session.gc_maxlifetime"); 
       // open database-connection 
       $dbHandle = mysqli_connect("localhost", "yourusername", "yourpassword", "yourdb");
       // return success 
       if(!$dbHandle) 
           return false; 
       $this->dbHandle = $dbHandle;
       echo "Connected to DB<br>";
       return true; 
    } 
    function close() { 
        echo "Called Close()<br>";
        $this->gc(ini_get('session.gc_maxlifetime')); 
        // close database-connection 
        return mysqli_close($this->dbHandle); 
    } 
    function read($sessID) {
        echo "Called session->read(sessID)<br>";
        $time = time();
        // fetch session-data 
        $query = "SELECT session_data AS d FROM ws_sessions 
                            WHERE session_id = '$sessID' 
                            AND session_expires > $time";
        $result = mysqli_query($this->dbHandle, $query) or die('Invalid query: ' . mysqli_error($this->dbHandle)); 
        // return data or an empty string at failure 
        if($row = mysqli_fetch_assoc($result)) {
            return $row['d']; 
        } else {
            return false;
        }
    }
    function write($sessID,$sessData) { 
        echo "Called session->write(sessID, sessData)<br>";
        // new session-expire-time 
        $newExp = time() + $this->lifeTime; 
        // is a session with this id in the database? 
        $query = "SELECT * FROM ws_sessions 
                  WHERE session_id = '$sessID'";
        $result = mysqli_query($this->dbHandle, $query) or die('Invalid query: ' . mysqli_error($this->dbHandle));
        // if yes, 
        if(mysqli_num_rows($result)) { 
            // ...update session-data 
            $query = "UPDATE ws_sessions 
                         SET session_expires = '$newExp', 
                         session_data = '$sessData' 
                         WHERE session_id = '$sessID'";
            $result = mysqli_query($this->dbHandle,$query) or die('Invalid query: ' . mysqli_error($this->dbHandle));
            // if something happened, return true 
            if(mysqli_affected_rows($this->dbHandle)) 
                return true; 
        } 
        // if no session-data was found, 
        else { 
            // create a new row 
            $query = "INSERT INTO ws_sessions ( 
                         session_id, 
                         session_expires, 
                         session_data) 
                         VALUES( 
                         '$sessID', 
                         '$newExp', 
                         '$sessData')";
             $result = mysqli_query($this->dbHandle,$query) or die('Invalid query: ' . mysqli_error($this->dbHandle));

            // if row was created, return true 
            if(mysqli_affected_rows($this->dbHandle)) 
                return true; 
        } 
        // an unknown error occured 
        return false; 
    } 
    function destroy($sessID) {
        echo "Called session->destroy(sessID)<br>";
        // delete session-data 
        $query = "DELETE FROM ws_sessions WHERE session_id = '$sessID'";
        $result = mysqli_query($this->dbHandle,$query) or die('Invalid query: ' . mysqli_error($this->dbHandle));
        // if session was deleted, return true, 
        if(mysqli_affected_rows($this->dbHandle)) 
            return true; 
        // ...else return false 
        return false; 
    } 
    function gc($sessMaxLifeTime) { 
        echo "Called session->gc(sessMaxLifeTime)<br>";
        // delete old sessions 
        $time = time();
        $query = "DELETE FROM ws_sessions WHERE session_expires < $time";
        $result = mysqli_query($this->dbHandle,$query) or die('Invalid query: ' . mysqli_error($this->dbHandle));
        // return affected rows 
        return mysqli_affected_rows($this->dbHandle); 
    } 
} 
$session = new session(); 
session_set_save_handler(array(&$session,"open"), 
                         array(&$session,"close"), 
                         array(&$session,"read"), 
                         array(&$session,"write"), 
                         array(&$session,"destroy"), 
                         array(&$session,"gc"));
// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');                       
session_start();

echo "<pre>";
echo "Testing Session: <br>";
$_SESSION['views'] = 1;
echo "Session views = ". $_SESSION['views'] . "<br>";
echo "Writing Session<br>";
$session->write(session_id(), $_SESSION['views']);
echo "</pre>";

?>