Home  >  Article  >  Backend Development  >  Starting a PHP session using MySQL_PHP Tutorial

Starting a PHP session using MySQL_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:58:25747browse

By default, PHP sessions are saved through files. This has the following disadvantages:

Session files are generally small, but the number of files is large. Saving many such small files in the file system is a waste of space and inefficient.
It is difficult for distributed sites to use session files to share sessions.
The session file method is not conducive to counting the session information of online users.
To solve the above problems, we can consider using a database to save session information.

For PHP development, saving sessions using MySQL is a very good choice. MySQL provides a table type Heap that is built in memory. If the amount of data per session is small, you can consider using this type of table to further optimize performance. However, the Heap type table has many limitations. For example, it does not support text type fields. Therefore, if the length of the session data record cannot be predicted, it is more appropriate to choose MyISAM. This type of table has no transaction processing overhead. Disk-based tables provide optimal performance.

The following is the structure of the sessions table:

DROP TABLE IF EXISTS `sessions`;
CREATE TABLE `sessions` (
`session_id` varchar(32) NOT NULL default ' ',
user_id` int (10) unsigned not null default' 0 ',
`data_value` text not null,
` lavisit` timestamp (14) not null,
Primary Key (` session_id`),
KEY `user_id` (`user_id`)
) TYPE=MyISAM;
PHP supports the user session module, and you can set a custom session processing function through session_set_save_handler. Because the default processing module is files, before using session_set_save_handler to set the session processing function, you must first use session_module_name('user') to tell PHP to use the user session module, and session_set_save_handler must be executed before session_start.

User session data is serialized in the session processing function. To take out one of the session variables, you can deserialize it. The default is the php serialization method. You can use session:: unserialize function to deserialize.

The following code defines a class that uses MySQL to handle PHP sessions. For the class_mysql.php used, please see "Super Simple But Super Practical PHP MySQL Class".

    〈?php
    /**
* @author Ma Bingyao
* @copyright (C) 2005 CoolCode.CN
*/

    require_once(“class_mysql.php“);

    class session {
        var $db;
        function session(&$db) {
            $this-〉db = &$db;
            session_module_name('user');
            session_set_save_handler(
                array(&$this, 'open'),
                array(&$this, 'close'),
                array(&$this, 'read'),
                array(&$this, 'write'),
                array(&$this, 'destroy'),
                array(&$this, 'gc')
            );
            session_start();
        }
        function unserialize($data_value) {
            $vars = preg_split(
                '/([a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*)|/',
                $data_value, -1, PREG_SPLIT_NO_EMPTY |
                PREG_SPLIT_DELIM_CAPTURE
            );
            for ($i = 0; $vars[$i]; $i++) {
                $result[$vars[$i++]] = unserialize($vars[$i]);
            }
            return $result;
        }
        function open($path, $name) {
            return true;
        }
        function close() {
            return true;
        }
        function read($session_id) {
            $session_id = $this-〉db-〉escape_string($session_id);
            if ($row = $this-〉db-〉query(“select * from `sessions` where `session_id` = '$session_id' limit 1“)) {
                return $row['data_value'];
            }
            else {
                $this-〉db-〉query(“insert into `sessions` set `session_id` = '$session_id'“);
                return ““;
            }
        }
        function write($session_id, $data_value) {
            $data = $this-〉unserialize($data_value);
            $session_id = $this-〉db-〉escape_string($session_id);
            $data_value = $this-〉db-〉escape_string($data_value);
            $this-〉db-〉query(“update `sessions` set “
                                    . “`user_id` = '{$data['user_id']}', “
                                    . “`data_value` = '$data_value', “
                                    . “`last_visit` = null “
                                    . “where `session_id` = '$session_id'“);
            return true;
        }
        function destroy($session_id) {
            $session_id = $this-〉db-〉escape_string($session_id);
            $this-〉db-〉query(“delete from `sessions` where `session_id` = '$session_id'“);
            return true;
        }
        function gc($lifetime) {
            $this-〉db-〉query(“delete from `sessions` where unix_timestamp(now()) - unix_timestamp(`last_visit`) 〉 $lifetime“);
            return true;
        }
        // get sessions by user_id
        function get($user_id) {
            $user_id = $this-〉db-〉escape_string($user_id);
            return $this-〉db-〉query(“select * from `sessions` where `user_id` = '$user_id'“);
        }
        // get sessions list
        function lists($page, $rows) {
            if ($page == 0) {
                return $this-〉db-〉query(“select * from `sessions` order by `user_id`“);
            }
            else {
                $start = ($page - 1) * $rows;
                return $this-〉db-〉query(“select * from `sessions` order by `user_id` limit $start, $rows“);
            }
        }
    }
?〉

The use of this class is very simple. Where session_start was originally used, just replace it with $session = new session($db). $db represents the database where the sessions table is located.

In addition, you can use the get method to get all the session information of a user, and the lists method to get the session list of all users. This makes it easy to manage user sessions.​

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317569.htmlTechArticleBy default, PHP sessions are saved through files. This has the following disadvantages: Session files are generally small, but the number of files is large, saving many...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn