The session is a very common PHP in the global variables, the following I will give beginners to introduce some of the usage of PHP session summary, I hope that some of the methods for beginners PHP friends will help Oh, the following people together to see it.
PHP Server default session storage is the way the file is stored, on the WINDOWS PHP default session server file stored under C:/windows/temp, *nix under the default storage in/TMP, If concurrent access is large or the session is built too much, there will be a lot of sess_xxxxxx-like session files in both directories, and too many files in the same directory can cause performance degradation and may result in file system errors eventually being attacked. In response to this situation, PHP's body provides a better solution.
Many friends may not have noticed that the php.ini inside the session Settings section has such an item:
; Session.save_path = "N; MODE; /path "
This setting provides us with a multi-level hash of the session storage directory, where "N" indicates the directory progression to be set, "MODE" means the permission attribute of the directory, the default is 600, is not set on Windows, *nix can not be set on the back, "/path" Represents the root directory path where session files are stored, such as the format we set to the following
Session.save_path = "2; /tmp/phpsession "
The above settings indicate that we put the/tmp/phpsession directory as the PHP session file root directory, in this directory to do two-level directory hash, each level of the directory is 0-9 and a-Z a total of 36 alphanumeric directory name, so that the directory to store the session can reach 36 * 36, believe that as a single server, this is fully sufficient, if your system architecture design for multiple servers to share session data, you can increase the directory level to 3 or more.
Note that PHP itself does not automatically create subdirectories, you need to create your own, the following automatically create directory code, you can make a reference. The following code automatically creates a level 3 subdirectory that you can modify yourself as needed.
| |
copy code |
set_time_limit (0); $string = ' 0123456789abcdefghijklmnopqrstuvwxyz '; $length = strlen ($string); Function MakeDir ($param) { if (!file_exists ($param)) { MakeDir (dirname ($param)); MkDir ($param); } } for ($i = 0; $i < $length; $i + +) { for ($j = 0; $j < $length; $j + +) { for ($k = 0; $k < $length; $k + +) { MakeDir ($string [$i]. ' /'. $string [$j]. ' /'. $string [$k]); } } } ?> |
There are two better solutions available:
1.session Warehousing
Using the Session_set_save_handler function
Role: Custom session storage mechanism.
Can be used to modify the session storage media, such as the session warehousing operations.
Instance Code
| The code is as follows |
Copy Code |
Class Sessionstable extends db{ protected $table _name = ' sessions '; Public Function __construct () { Parent::__construct (); Session_set_save_handler ( Array ($this, ' Sess_open '), Array ($this, ' sess_close '), Array ($this, ' sess_read '), Array ($this, ' sess_write '), Array ($this, ' Sess_destroy '), Array ($this, ' sess_gc ') ); Session_Start (); } Public Function Sess_open ($save _path, $session _name) { return true; } Public Function Sess_close () { return true; } Public Function Sess_read ($sess _id) { $sql = "Select * FROM {$this->gettable ()} where sess_id= ' {$sess _id} '"; $row = $this->getrow ($sql); return $row [' Sess_data ']; } Public Function Sess_write ($sess _id, $sess _data) { $expire = time (); $sql = "INSERT INTO {$this->gettable ()} values (' {$sess _id} ', ' {$sess-_data} ', ' {$expire} ') on duplicate key Update Sess_data= ' {$sess _data} ', expire= ' {$expire} '; return $this->query ($sql); } Public Function Sess_destroy ($sess _id) { $sql = "Delete from {$this->gettable ()} where sess_id= ' {$sess _id} '"; return $this->query ($sql); } Public Function sess_gc ($life _time) { $expire = Time ()-$life _time; $sql = "Delete from {$this->gettable ()} where expire < {$expire}"; return $this->query ($sql); } }
|
2. Use Memcache to store session
Method I: Global settings in php.ini
Session.save_handler = Memcache
Session.save_path = "tcp://127.0.0.1:11211"
Method II: Use Ini_set settings in one application
Ini_set ("Session.save_handler", "memcache");
Ini_set ("Session.save_path", "tcp://127.0.0.1:11211");
Use multiple memcached servers separated by commas "," and, as described in the memcache::addserver () documentation, can take additional parameters "persistent", "weight", "timeout", "Retry_ Interval "And so on, like this:" Tcp://host1:port1?persistent=1&weight=2,tcp://host2:port2 ".
1. How to operate the session in PHP:
Session_Start (); Use this function to open the session function
$_session//using predefined global variables to manipulate data
Use unset ($_session[' key ")//Destroy the value of a SESSION
Simple to operate, everything is implemented by the server; because it's in the background, everything looks safe. But what mechanism does the session adopt, and how is it implemented, and how to maintain the state of the session?
2.session implementation and how it works
The browser and server use HTTP stateless communication, in order to maintain the state of the client, using the session to achieve this purpose. But how does the service end up labeling different clients or users?
Here we can use an example of life, if you attend a party, meet a lot of people, you will take what way to distinguish different people! You may be based on the face shape, or may be based on the user's name,
Or a person's identity card, that is, a unique logo. In the session mechanism, it also uses a unique session_id to mark different users, the difference is: the browser every request will be brought
The session_id generated by the server for it.
A brief introduction to the process: When the client accesses the server, the server sets the session according to the requirements, saves the conversation information on the server, and passes the session_id that marked the session to the client browser.
The browser keeps the session_id in memory (there are other ways of storing it, for example, written in a URL), which we call a cookie without expiration time. When the browser is closed, the cookie is cleared and there is no temporary cookie file for the user.
After the browser each request will add this parameter value, then the server according to this session_id, can obtain the client's data status.
If the client browser shuts down unexpectedly, the session data saved by the server is not released immediately, the data will still exist, as long as we know the session_id, we can continue to obtain the session information by request, but this time the backstage session still exists, But the session was saved with an expiration
Time, and when there is no client request beyond the specified time, he clears the session.
The following describes the session storage mechanism, the default session is saved in files, that is, the file to save the session data. In PHP mainly based on the configuration of php.ini Session.save_handler
To choose how you want to save the session.
Here by the way, if you want to do the server LVS, that is, more than one server, we generally use the memcached way session, otherwise it will cause some requests can not find the session.
A simple memcache configuration:
Session.save_handler = Memcache
Session.save_path = "tcp://10.28.41.84:10001"
Of course, if you must use the files file cache, we can make the file for NFS, and all the saved session files are located in one place.
Just now the Session-id returned to the user is finally saved in memory, where we can also set the parameters to save them in the user's URL.
thinkphp Official documentation
01.start Start session
02.pause Pause Session
03.clear Clear Session
04.destroy destroying session
05.get Get Session value
06.getLocal Get Private Session value
07.set Setting Session Value
08.setLocal Setting Private Session value
09.name Get or set Session_name
10.is_set whether to set session value
11.is_setlocal whether to set private session value
12.id Get or set session_id
13.path Get or set Session_save_path
14.setExpire Set Session Expiration time
15.setCookieDomain setting a valid domain name
16.setCallback sets the callback function when the session object is deserialized
Examples of the most common operating methods:
Code: 01.//detect if a session variable exists
| The code is as follows |
Copy Code |
02.session::is_set (' name '); 03. Assigning a value to a session variable 04. Session::set (' name ', ' value '); 05. Get Session variable 06. Session::get (' name '); |
and session-related configuration parameters:
Code:
| |
copy code |
| 01. ' Session_name ' = ' thinkid ',//default session_name 02. ' session_path ' = ', '//using the default SESSION save PATH 03. ' session_type ' = ' file ',//default SESSION type supports DB and File 04. ' session_expire ' = ' 300000 ',//default SESSION validity 05. ' session_table ' = ' think_session ',//Database SESSION table name 06. ' session_callback ' = ', '//' callback method for deserializing an object |
Where the Session_name parameter needs to be noted, if you need to not share the value of the pass session between different items, set a different value, otherwise leave the same default value.
If you set the same value for Session_name, but want to create a private session space based on the project, what should I do with it? Thinkphp also supports private session operations with the project session space, taking the previous common operations as an example, we changed as follows:
Code:
| The code is as follows |
Copy Code |
01.//detects if the session variable exists (current project is valid) 02.session::is_setlocal (' name '); 03. Assign a value to the session variable (current project is valid) 04. Session::setlocal (' name ', ' value '); 05. Get Session variable (current project is valid) 06. Session::getlocal (' name '); |
In this way, the session operation with the global will not conflict, can be used for some special situations need.
thinkphp support the database mode of the session operation, set the value of Session_type db is OK, if you use the database method, also make sure to set the value of session_table, and import the following DDL to your Database (with MySQL as an example):
Code:
| The code is as follows |
Copy Code |
01.CREATE TABLE ' think_session ' ( 02. ' ID ' int (one) unsigned not NULL auto_increment, 03. ' session_id ' varchar (255) is not NULL, 04. ' Session_expires ' int (one) is not NULL, 05. ' Session_data ' blob, 06. PRIMARY KEY (' id ') 07.) |
Note that the DB session mode database connection is connected using the database configuration information for the project. In addition to the database mode, you can also add other ways of the session save mechanism, such as memory mode, Memcache mode, etc., we just add the corresponding filter on the line, using the Session_set_save_handler method, The specific method defines the implementation of the FilterSessionDb.class.php file below the reference Think.Util.Filter.
Made a simple landing judgment
The session value is given after login, so that the value of session is False if it is not null
| The code is as follows |
Copy Code |
$_session[c (' User_auth_key ')] = $logInFind [' id '];
|
where [C (' User_auth_key ')] is the built-in method and function class for thinkphp. Default is empty when the config.php file is not configured
$loginfind[' id ' to take out the account value assigned to it, the default is to close the page session automatically deleted disappeared!
Other pages use the following format to determine
| The code is as follows |
Copy Code |
if (!isset ($_session[c (' User_auth_key '))) {//isset is the detection variable is assigned value! $this->redirect (' login ', ' login '); Go to registration page }
|
http://www.bkjia.com/PHPjc/632699.html www.bkjia.com true http://www.bkjia.com/PHPjc/632699.html techarticle The session is a very common PHP in the global variables, I would like to give beginners to introduce some summary of the use of PHP session, I hope that some methods of beginners PHP friends will help Oh, the next ...