Parse phpsession_set_save_handler function usage (mysql ). Copy the code as follows :? Php * file description @ filename: session. class. php @ description: Online database storage
The code is as follows:
/* ============================ File description ========== ======================================
@ Filename: session. class. php
@ Description: the database saves the online user session to implement the online user function!
@ Notice: the session expiration time is one hour, because our site uses cookies (valid for 1 hour) to log on.
Therefore, we only record the user logon time, instead of refresh once.
The action of deleting session records in the database occurs when the user times out and executes the file or exits normally (session_destory)
@ Database: 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 storage method. this is required! Unless it is set in the Php. ini file
Session_set_save_handler (
Array (& $ this, 'open'), // run
Array (& $ this, 'close'), // it is executed when the script is executed or session_write_close () or session_destroy () is called, that is, it is executed after all session operations are completed.
Array (& $ this, 'read'), // it is executed when session_start () is run, because the current session data is read during session_start.
Array (& $ this, 'write'), // this method is executed when the script ends and session_write_close () is used to force the SESSION data to be submitted.
Array (& $ this, 'deststroy'), // execute when running session_destroy ()
Array (& $ this, 'gc ') // The execution probability is determined by the session. gc_probability and session. the value of gc_pisor is determined by the time when session_start runs open, read, and gc successively after open and read.
);
Session_start (); // This is also required. to open a session, it must be executed after session_set_save_handler.
}
Function unserializes ($ 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; isset ($ vars [$ I]); $ I ++ ){
$ Result [$ vars [$ I ++] = unserialize ($ vars [$ I]);
}
Return $ result;
}
Function open ($ path, $ name ){
Return true;
}
Function close (){
$ This-> gc ($ this-> lasttime );
Return true;
}
Function read ($ SessionKey ){
$ SQL = "SELECT uid FROM sessions WHERE session_id = '". $ SessionKey. "'limit 1 ";
$ Query = $ this-> db-> query ($ SQL );
If ($ row = $ this-> db-> fetch_array ($ query )){
Return $ row ['uid'];
} Else {
Return "";
}
}
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. "'submit 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 'session' set 'session _ id' = '$ sessionkey', uid = '". $ data ['webid']. "', last_visit = '". time (). "'");
}
Return true;
} Else {
/* $ SQL = "update 'session' 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 'session' where 'session _ id' = '$ sessionkey '");
Return true;
}
Function gc ($ lifetime ){
$ This-> db-> query ("delete from 'session' where unix_timestamp (now ()-'Last _ visit'> '". $ this-> lasttime. "'");
Return true;
}
}
?>
The following describes the session configuration in php. ini:
Session. save_handler = "files"
The name of the processor that stores and retrieves the data associated with the session. The default value is file ("files ").
If you want to use a custom processor (such as a database-based processor), you can use "user ".
There is a PostgreSQL processor: http://sourceforge.net/projects/phpform-ext/
Session. save_path = "/tmp"
The parameter passed to the storage processor. For the files processor, this value is the path for creating the session data file.
In Windows, the default path is a temporary folder.
You can use "N [MODE]/path" to define this path (N is an integer ).
N indicates that sub-directories of N layers are used instead of all data files stored in one directory.
[MODE] (optional) it must use an octal number. the default value is 600 (= 384), indicating the maximum number of session files saved in each directory.
This is a good idea to improve the performance of a large number of sessions.
Note 0: double quotation marks on both sides of "N [MODE]/path" cannot be omitted.
Note 1: [MODE] does not rewrite the umask of the process.
Note 2: php does not automatically create these folder structures. Use the mod_files.sh script in the ext/session directory to create the file.
Note 3: If the folder can be accessed by insecure users (such as the default "/tmp"), security vulnerabilities may occur.
Note 4: automatic garbage collection fails when N> 0. for details, refer to the following section on garbage collection.
Session. name = "PHPSESSID"
The session ID used in the cookie. it can only contain letters and numbers.
Session. auto_start = Off
The session is automatically initialized when the customer accesses any page, which is disabled by default.
Because the class definition must be loaded before the session starts, if this option is enabled, you cannot store objects in the session.
Session. serialize_handler = "php"
Php is a standard serialization/deserialization processor.
You can also use "php_binary ". When WDDX support is enabled, only "wddx" can be used ".
Session. gc_probability = 1
Session. gc_pisor = 100
Defines the probability of starting the garbage collection program each time a session is initialized.
The formula for calculating the collection probability is as follows: session. gc_probability/session. gc_pisor
The more frequently a session page is accessed, the smaller the probability is. Recommended value: 1/1000 ~ 5000.
Session. gc_maxlife time = 1440
After the number of seconds specified by this parameter is exceeded, the stored data will be treated as 'spam 'and cleared by the garbage collection program.
The criterion is the last time the data is accessed (for the FAT file system, the last time the data is refreshed ).
If multiple scripts share the same session. save_path directory but session. gc_maxlifetime is different,
The minimum value in all session. gc_maxlifetime commands prevails.
If multiple sub-directories are used to store data files, the garbage collection program will not start automatically.
You must use a shell script, cron item, or other method you have compiled to perform garbage collection.
For example, the following script is equivalent to setting "session. gc_maxlifetime = 1440" (24 minutes ):
Cd/path/to/sessions find-cmin + 24 | xargs rm
Session. referer_check =
If the "Referer" field in the request header does not contain the specified string, the session ID is considered invalid.
Note: If the "Referer" field does not exist in the request header, the session ID is still valid.
The default value is null, that is, no check is performed (all are considered valid ).
Session. entropy_file = "/dev/urandom"
Additional external high-entropy resources (files) used to create Session IDs ),
For example, "/dev/random" or "/dev/urandom" on UNIX systems"
Session. entropy_length = 0
The number of bytes read from a resource with high entropy (recommended value: 16 ).
Session. use_cookies = On
Whether to use cookies to save the session ID on the client
Session. use_only_cookies = Off
Whether to use the cookie to save the session ID on the client
Enabling this option can avoid the security issues caused by passing sessions through URLs.
However, the client that disables the Cookie will make the session unable to work.
Session. cookie_lifetime = 0
The Cookie validity period (in seconds) for passing session ids. 0 indicates that the Cookie is valid only when the browser opens.
Session. cookie_path = "/"
The path of the Cookie that transmits the session ID.
Session. cookie_domain =
Cookie scope for passing session IDs.
The default value is null, indicating the host name generated according to the cookie specification.
Session. cookie_secure = Off
Whether to send cookies only through secure connections (https.
Session. cookie_httponly = Off
Whether to add the httpOnly flag to the cookie (only HTTP protocol access is allowed ),
This will cause client scripts (such as JavaScript) to be unable to access the cookie.
Enabling this command can effectively prevent session IDs from being hijacked through XSS attacks.
Session. cache_limiter = "nocache"
Set to {nocache | private | public} to specify the cache control mode of the session page,
Or leave it blank to prevent the http response header from sending commands that disable caching.
Session. cache_expire = 180
Specify the validity period of the session page in the client cache (minutes)
Session. cache_limiter = nocache, the setting here is invalid.
Session. use_trans_sid = Off
Whether to use the plaintext to display the SID (Session ID) in the URL ).
It is disabled by default because it brings security risks to your users:
1-the user may send a URL containing a valid sid via email/irc/QQ/MSN... The channel is told to others.
2-a URL containing a valid sid may be saved on a public computer.
3-users may save URLs with fixed sid in their favorites or browsing history records.
URL-based session management is always more risky than Cookie-based session management, so it should be disabled.
Session. bug_compat_42 = On
Session. bug_compat_warn = On
In versions earlier than PHP4.2, there is an unspecified "BUG ":
You can initialize global session variables even if register_globals is Off,
If you use this feature in versions later than PHP4.3, a warning is displayed.
We recommend that you disable 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)
SHA-1 is recommended.
Session. hash_bits_per_character = 4
Specifies the number of bits in each character in the SID string,
These binary numbers are the calculation results of the hash function.
4: 0-9, a-f
5: 0-9, a-v
6: 0-9, a-z, A-Z ,"-",","
Recommended value: 5
Url_rewriter.tags = "a = href, area = href, frame = src, form =, fieldset ="
This command is a core part of PHP and does not belong to the Session module.
Specifies which HTML tags to override to include SID (only valid when session. use_trans_sid = On)
Form and fieldset are special:
If you include them, the URL Rewrite will add a hidden"", Which contains information that should be appended to the URL.
To comply with the XHTML standard, remove the form item and add
Mark.
Note: all valid items require an equal sign (even if there is no value after ).
The recommended value is "a = href, area = href, frame = src, input = src, form = fakeentry ".
The http://www.bkjia.com/PHPjc/327928.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/327928.htmlTechArticle code is as follows :? Php/* = =======================================@ filename: session. class. php @ description: Online database storage...