


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) 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

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.