Parsing PHP session_set_save_handler function usage (mysql) _php tutorial

Source: Internet
Author: User
Copy CodeThe code is as follows:
/*============================ File Description ========================================
@filename: session.class.php
@description: Database Save Online User session, realize online user function!
@notice: The session expires one hours because our site is logged in using a cookie (valid for 1 hours).
So we only log the time that the user logged in, not the update once.
The action to delete a session record in the database occurs when the user times out and executes the file or exits normally (session_destory)
@database: Database:sessions Field:sessionid (Char32), UID (int10), Last_visit (int10)
=============================================================================
*/
Class Session {
Private $db;
Private $lasttime =3600;//Time-out: one hours
Function session (& $DB) {
$this->db = & $db;
Session_module_name (' user '); Session file Save way, this is necessary! Unless you set the php.ini file in the
Session_set_save_handler (
Array (& $this, ' Open '),//execute at Run session_start ()
Array (& $this, ' close '), executed when the script executes or calls Session_write_close () or Session_destroy (), which is executed after all sessions have completed
Array (& $this, ' read '), executed at Run Session_Start (), because at Session_Start, the current session data is read
Array (& $this, ' write '),//This method executes when the script ends and uses session_write_close () to force the session data to be committed
Array (& $this, ' Destroy '),//execute at Run Session_destroy ()
The array (& $this, ' GC ')//execution probabilities are 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 successively
);
Session_Start (); This is also necessary, open the session, must be executed behind the 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 ');
$db 1=new dbcom ();
Make a connection to the database ... now
$db 1->connect (Db_server, Db_server_username, Db_server_password, db_database);
$db 1->query ("Set names UTF8");
$this->db= $db 1;
$SessionArray = Addslashes ($VArray);
$data = $this->unserializes ($VArray);
$sql 0 = "Select uid from sessions WHERE session_id = '". $SessionKey. "' Limit 1";
$query 0 = $this->db->query ($sql 0);
if ($this->db->num_rows ($query 0) <=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;
}
}
?>

Here are the configuration instructions for the session in PHP.ini:
Session.save_handler = "Files"
The processor name that stores and retrieves the data associated with the session. The default is file ("files").
If you want to use a custom processor (such as a database-based processor), "User" is available.
There is a processor that uses PostgreSQL: http://sourceforge.net/projects/phpform-ext/

Session.save_path = "/tmp"
The parameters passed to the storage processor. For the files processor, this value is the path to the creation of the session data file.
The default is the temporary folder path under Windows.
You can use the "N[mode]/path" pattern to define the path (N is an integer).
n represents a subdirectory with n-level depth, instead of saving all data files in one directory.
[MODE] optional, you must use 8 decimal, default 600 (=384), which indicates the maximum number of session files saved per directory.
This is a good idea to improve the performance of a lot of sessions.
Note 0: Double quotes on both sides of "N[mode]/path" cannot be omitted.
Note 1: [MODE] does not overwrite the umask of the process.
Note 2:php does not automatically create these folder structures. Please use the mod_files.sh script under the Ext/session directory to create it.
Note 3: If the folder can be accessed by insecure users (such as the default "/tmp"), then a security vulnerability will be created.
Note 4: Automatic garbage collection will expire when n>0, see the Garbage collection section below for details.

Session.name = "Phpsessid"
The session ID used in the cookie identifies the name and can contain only letters and numbers.

Session.auto_start = Off
The session is automatically initialized when the customer accesses any page, and is disabled by default.
Because the class definition must be loaded before the session is started, you cannot store the object in the session if this option is turned on.

Session.serialize_handler = "PHP"
The processor used to serialize/deserialize data, PHP is the standard serialization/deserialization processor.
You can also use "php_binary". When WDDX support is enabled, only "WDDX" will be used.

session.gc_probability = 1
Session.gc_divisor = 100
Defines the probability of starting a garbage collection program each time the session is initialized.
The calculation formula for this collection probability is as follows: Session.gc_probability/session.gc_divisor
The more frequently you access a session page, the smaller the probability should be. The recommended value is 1/1000~5000.

Session.gc_maxlifetime = 1440
After the number of seconds that this parameter refers to, the saved data is treated as ' garbage ' and cleaned up by the garbage collection program.
The judging criteria is the last time the data was accessed (for the FAT file system is the last time to refresh the data).
If multiple scripts share the same Session.save_path directory but session.gc_maxlifetime are different,
Then the minimum value in all session.gc_maxlifetime directives will prevail.
If you use multi-level subdirectories to store data files, the garbage collector does not start automatically.
You must use a shell script, cron item, or other method that you write yourself to perform garbage collection.
For example, the following script is equivalent to setting the "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 string specified here, the session ID is considered invalid.
Note: If the "Referer" field does not exist at all in the request header, the session ID will still be considered valid.
The default is null, i.e. no check (all considered valid).

Session.entropy_file = "/dev/urandom"
An additional external high-entropy resource (file) for creating the session ID,
For example, "/dev/random" or "/dev/urandom" on Unix systems

Session.entropy_length = 0
The number of bytes read from the High Entropy resource (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 save the session ID only on the client using cookies
Turn this option on to avoid the security issues associated with using URL delivery sessions.
However, a client that disables cookies causes the session to not work.

Session.cookie_lifetime = 0
The lifetime of the cookie that passes the session ID (in seconds), 0 means only valid during browser opening.

Session.cookie_path = "/"
The cookie action path that passes the session ID.

Session.cookie_domain =
The cookie scope that passes the session ID.
The default is null to indicate the hostname generated by the cookie specification.

Session.cookie_secure = Off
Whether to send cookies only via secure connection (HTTPS).

Session.cookie_httponly = Off
Whether to add the HTTPONLY flag in the cookie (only allow HTTP protocol access),
This causes client script (JavaScript, and so on) to not be able to access the cookie.
Opening this directive effectively prevents the hijacking of session IDs through XSS attacks.

Session.cache_limiter = "NoCache"
Set to {nocache|private|public} to specify the cache control mode for the session page.
or set to blank to prevent the command that disables caching from being sent in the HTTP reply header.

Session.cache_expire = 180
Specify the expiration date of the session page in the client cache (minutes)
Session.cache_limiter=nocache, this setting is not valid here.

Session.use_trans_sid = Off
Whether to display the SID (session ID) in the URL using plaintext.
The default is forbidden because it poses a security risk to your users:
1-The user may include a valid SID URL via email/irc/qq/msn ... Way to tell other people.
2-URLs that contain valid SIDS may be saved on the public computer.
3-users may save URLs with fixed SID in their favorites or browsing history.
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
The previous version of PHP4.2 has a "BUG" that is not noted:
Allows the initialization of global session variables even in register_globals=off cases,
If you use this feature in the version after PHP4.3, a warning is displayed.
We recommend that you close the BUG and display a warning.

session.hash_function = 0
Generates a hash algorithm for the SID. SHA-1 's security is a bit higher.
0:MD5 (BITS)
1:sha-1 (BITS)
It is recommended to use SHA-1.

Session.hash_bits_per_character = 4
Specifies how many bits characters each word in the SID string,
These binary numbers are the result of the hash function's operation.
4:0-9, A-f
5:0-9, A-v
6:0-9, A-Z, a-Z, "-", ","
Recommended value is 5

Url_rewriter.tags = "a=href,area=href,frame=src,form=,fieldset="
this directive is part of the PHP core and does not belong to the session module.
Specifies which HTML tags are overridden to contain SIDS (only valid when session.use_trans_sid=on)
form and fieldset are special:
If you include them, The URL rewrite adds a hidden "" that contains information that should be appended to the URL.
If you want to conform to the XHTML standard, remove the form entry and precede the form field with

The tag.
Note: All valid entries require an equal sign (even if no value is followed). The
recommended value is "A=href,area=href,frame=src,input=src,form=fakeentry".

http://www.bkjia.com/phpjc/327928.html www.bkjia.com true Span id= "Isbasedonurl" itemprop= "Isbasedonurl" >http://www.bkjia.com/phpjc/327928.html techarticle Copy the code code as follows:? PHP/*============== ============== file Description ======================================== @filename: session.class.php @description: Database save online with ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.