Parsing the usage of php session_set_save_handler function (mysql)_PHP tutorial

WBOY
Release: 2016-07-21 15:02:29
Original
897 people have browsed it

Copy code The code is as follows:

/*==============================File description===== ===================================
@filename: session.class.php
@ description: The database saves online user sessions to implement online user functions!
@notice: The session expiration time is one hour because our site uses cookies (valid time is 1 hour) to log in.
Therefore, we only record the time when the user logs in, instead of refreshing and updating once.
sessions field:sessionid(char32),uid(int10),last_visit(int10)
============================== ===============================================
*/
class session {
private $db;
private $lasttime=3600;//Timeout: one hour
function session(&$db) {
$this-> db = &$db;
session_module_name('user'); //session file saving method, this is a must!Unless
is set in the Php.ini file session_set_save_handler(
, //Executed when the script execution is completed or session_write_close() or session_destroy() is called, that is, it is executed after all session operations are completed
                                                                                                                     Executed when session_start, because the current session data will be read when session_start. (&$this, 'destroy'), //Execute
when running session_destroy()       array(&$this, 'gc') //The execution probability is determined by the values ​​of session.gc_probability and session.gc_divisor, and the timing is After open, read, session_start will execute open, read and gc one after another unserializes($data_value) {
                                                                                                                                               data_value, -1, PREG_SPLIT_NO_EMPTY |
               PREG_SPLIT_DELIM_CAPTURE                                 $result[$vars[$ i++]] = unserialize($vars[$i]);
                                                             ; > }
function close() {
$this->gc($this->lasttime);
return true;
}
function read($SessionKey){
            $sql = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1"; $row=$this->db->fetch_array($query)){
                                                                                                                                               >         }
     function write($SessionKey,$VArray) {
         require_once(MRoot.DIR_WS_CLASSES .'db_mysql_class.php');
        $db1=new DbCom();
       // make a connection to the database... now
        $db1->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);
        $db1->query("set names utf8");
        $this->db=$db1;
        $SessionArray = addslashes($VArray);
         $data=$this->unserializes($VArray);  
                          $sql0 = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1";
         $query0 =$this->db->query($sql0);
         if($this->db->num_rows($query0)<=0){
             if (isset($data['webid']) && !empty($data['webid'])) {
                $this->db->query("insert into `sessions` set `session_id` = '$SessionKey',uid='".$data['webid']."',last_visit='".time()."'");
             }   
                    return true;
         }else{
             /*$sql = "update `sessions` set ";
             if(isset($data['webid'])){
             $sql .= "uid = '".$data['webid']."', " ;
             }
             $sql.="`last_visit` = null "
                   . "where `session_id` = '$SessionKey'";
                               $this->db->query($sql); */
             return true;
         }   
     }
   function destroy($SessionKey) {
      $this->db->query("delete from `sessions` where `session_id` = '$SessionKey'");
      return true;
    }
    function gc($lifetime) {
        $this->db->query("delete from `sessions` where unix_timestamp(now()) -`last_visit` > '".$this->lasttime."'");
        return true;
    }
     }
 ?>

下面是php.ini中session的配置说明:
session.save_handler = "files"
 存储和检索与会话关联的数据的处理器名字。默认为文件("files")。
 如果想要使用自定义的处理器(如基于数据库的处理器),可用"user"。
 有一个使用PostgreSQL的处理器:http://sourceforge.net/projects/phpform-ext/

session.save_path = "/tmp"
 传递给存储处理器的参数。对于files处理器,此值是创建会话数据文件的路径。
 Windows下默认为临时文件夹路径。
 你可以使用"N[MODE]/path"这样模式定义该路径(N是一个整数)。
 N表示使用N层深度的子目录,而不是将所有数据文件都保存在一个目录下。
 [MODE]可选,必须使用8进制数,默认600(=384),表示每个目录下最多保存的会话文件数量。
 这是一个提高大量会话性能的好主意。
 注意0: "N[MODE]/path"两边的双引号不能省略。
 注意1: [MODE]并不会改写进程的umask。
 注意2: php不会自动创建这些文件夹结构。请使用ext/session目录下的mod_files.sh脚本创建。
 注意3: 如果该文件夹可以被不安全的用户访问(比如默认的"/tmp"),那么将会带来安全漏洞。
 注意4: 当N>0时自动垃圾回收将会失效,具体参见下面有关垃圾搜集的部分。

session.name = "PHPSESSID"
用在cookie里的会话ID标识名,只能包含字母和数字。

session.auto_start = Off
 在客户访问任何页面时都自动初始化会话,默认禁止。
 因为类定义必须在会话启动之前被载入,所以若打开这个选项,你就不能在会话中存放对象。

session.serialize_handler = "php"
 用来序列化/解序列化数据的处理器,php是标准序列化/解序列化处理器。
 另外还可以使用"php_binary"。当启用了WDDX支持以后,将只能使用"wddx"。

session.gc_probability = 1
session.gc_divisor = 100
 定义在每次初始化会话时,启动垃圾回收程序的概率。
 这个收集概率计算公式如下:session.gc_probability/session.gc_divisor
 对会话页面访问越频繁,概率就应当越小。建议值为1/1000~5000。

session.gc_maxlifetime = 1440
 超过此参数所指的秒数后,保存的数据将被视为'垃圾'并由垃圾回收程序清理。
 判断标准是最后访问数据的时间(对于FAT文件系统是最后刷新数据的时间)。
 如果多个脚本共享同一个session.save_path目录但session.gc_maxlifetime不同,
 那么将以所有session.gc_maxlifetime指令中的最小值为准。
 如果使用多层子目录来存储数据文件,垃圾回收程序不会自动启动。
 你必须使用一个你自己编写的shell脚本、cron项或者其他办法来执行垃圾搜集。
 比如,下面的脚本相当于设置了"session.gc_maxlifetime=1440" (24分钟):
 cd /path/to/sessions find -cmin +24 | xargs rm

session.referer_check =
 如果请求头中的"Referer"字段不包含此处指定的字符串则会话ID将被视为无效。
 注意:如果请求头中根本不存在"Referer"字段的话,会话ID将仍将被视为有效。
 默认为空,即不做检查(全部视为有效)。

session.entropy_file = "/dev/urandom"
 附加的用于创建会话ID的外部高熵值资源(文件),
 例如UNIX系统上的"/dev/random"或"/dev/urandom"

session.entropy_length = 0
 从高熵值资源中读取的字节数(建议值:16)。

session.use_cookies = On
 是否使用cookie在客户端保存会话ID

session.use_only_cookies = Off
 是否仅仅使用cookie在客户端保存会话ID
 打开这个选项可以避免使用URL传递会话带来的安全问题。
 但是禁用Cookie的客户端将使会话无法工作。

session.cookie_lifetime = 0
 传递会话ID的Cookie有效期(秒),0 表示仅在浏览器打开期间有效。

session.cookie_path = "/"
 传递会话ID的Cookie作用路径。

session.cookie_domain =
Pass the cookie scope of the session ID.
The default is empty to indicate the host name generated according to the cookie specification.

session.cookie_secure = Off
Whether to only send cookies through secure connections (https).

session.cookie_httponly = Off
Whether to add the httpOnly flag in the cookie (only HTTP protocol access is allowed),
This will cause client scripts (JavaScript, etc.) to be unable to access the cookie.
Turning on this command can effectively prevent session ID hijacking through XSS attacks.

session.cache_limiter = "nocache"
Set to {nocache|private|public} to specify the cache control mode of the session page,
or set to empty to prevent HTTP response headers Send the command to disable caching.

session.cache_expire = 180
Specifies the validity period (minutes) of the session page in the client cache
When session.cache_limiter=nocache, this setting is invalid.

session.use_trans_sid = Off
Whether to use clear code to display SID (session ID) in the URL.
It is prohibited by default because it will bring security risks to your users:
1- Users may tell other people the URL containing a valid sid through email/irc/QQ/MSN....
2- URLs containing valid sids may be saved on public computers.
3- Users may save URLs with fixed sids in their favorites or browsing history.
URL-based session management always carries more risks than cookie-based session management and should be disabled.

session.bug_compat_42 = On
session.bug_compat_warn = On
Versions before PHP4.2 have an unspecified "BUG":
Even when register_globals=Off It is also allowed to initialize global session variables.
If you use this feature in versions after PHP 4.3, a warning will be displayed.
It is recommended to close this "BUG" and display a warning.

session.hash_function = 0
Hash algorithm for generating SID. SHA-1 is more secure
0: MD5 (128 bits)
1: SHA-1 (160 bits)
It is recommended to use SHA-1.

session.hash_bits_per_character = 4
Specifies how many bits are saved in each character in the SID string.
These binary numbers are the results of the hash function.
4: 0-9, a-f
5: 0-9, a-v
6: 0-9, a-z, A-Z, "-", ","
The recommended value is 5

url_rewriter.tags = "a=href,area=href,frame=src,form=,fieldset="
This command belongs to the core part of PHP and does not belong to the Session module.
Specify which HTML tags to rewrite to include SID (only valid when session.use_trans_sid=On)
Form and fieldset are special:
If you include them, URL rewriter A hidden "" will be added, which contains additional information that should be appended to the URL.
If you want to comply with XHTML standards, please remove the form item and add

tags before and after the form fields.
Note: All legal items require an equal sign (even if there is no value after it).
The recommended value is "a=href, area=href, frame=src, input=src, form=fakeentry".

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327928.htmlTechArticleCopy the code as follows: ?php /*=============== =============File Description==================================== ===== @filename: session.class.php @description: The database is saved online...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!