


Parsing the usage of php session_set_save_handler function (mysql)_PHP tutorial
/*==============================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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.
