Session is a common global variable in php. Next I will introduce some usage Summary of php session for beginners. I hope some methods will help php beginners, let's take a look.
The default session storage method of the PHP server is file storage. On Windows, the default Session Server File of PHP is stored in C:/WINDOWS/Temp, and * NIX is stored in/tmp by default, if the number of concurrent accesses is large or the number of sessions is too large, there will be a large number of session files similar to sess_xxxxxx in these two directories. Too many parts in the same directory will cause performance degradation, this vulnerability may cause a file system error. In this case, PHP provides a better solution.
Many friends may not have noticed the Session settings in php. ini:
; Session. save_path = "N; MODE;/path"
This setting provides a multi-level hash for the session storage directory. "N" indicates the directory level to be set, and "MODE" indicates the permission attribute of the directory. The default value is 600, in WINDOWS, you do not need to set it. * You do not need to set it on NIX. The "/path" next to it indicates the root directory path of the session file. For example, we set it to the following format.
Session. save_path = "2;/tmp/phpsession"
The above settings indicate that the/tmp/phpsession directory is used as the root directory for storing php session files, and two levels of directories are hashed in this directory, each level of directory is 0-9 and a-z with a total of 36 letters and numbers as the directory name. In this way, the directory for storing sessions can reach 36*36. I believe that as a single server, this is enough. If your system architecture is designed to share session data with multiple servers, you can increase the directory level to three or more.
Note that php does not automatically create sub-directories. You need to create sub-directories by yourself. The following code automatically creates directories for your reference. The following code automatically creates three levels of sub-directories. You can modify them as needed.
| The Code is as follows: |
Copy code |
<? Php
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]);
}
}
}
?>
|
Two better solutions are provided below:
1. session receiving
Use the session_set_save_handler Function
Purpose: Customize the SESSION storage mechanism.
It can be used to modify the session storage medium, such as loading sessions.
Instance code
| The Code is as follows: |
Copy code |
Class sessionsTable extends db {
Protected $ table_name = 'session ';
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 sessions
Method I: global settings in php. ini
Session. save_handler = memcache
Session. save_path = "tcp: // FIG: 11211"
Method II: Use ini_set settings in an application
Ini_set ("session. save_handler", "memcache ");
Ini_set ("session. save_path", "tcp: // 127.0.0.1: 11211 ");
Multiple memcached servers are separated by commas (,), which are the same as those described in the Memcache: addServer () document, you can include additional parameters such as "persistent", "weight", "timeout", and "retry_interval". For example, "tcp: // host1: port1? Persistent = 1 & weight = 2, tcp: // host2: port2 ".
1. How to operate the session in php:
Session_start (); // use this function to enable the session function.
$ _ SESSION // use predefined global variables to operate data
Use unset ($ _ SESSION ['key']) // destroy the value of a session
In simple operations, everything is implemented by the server; because the processing is in the background, everything looks safe. But what kind of mechanism does the session adopt and how does it maintain the session state?
2. session implementation and working principle
The browser and server use http stateless communication. To maintain the client status, use session to achieve this goal. But how does the server mark different clients or users?
Here we can use an example in our daily life. If you have met many people at a party, how will you differentiate different people! Depending on your face or user name,
Or a person's ID card, that is, a unique identifier. In the session mechanism, a unique session_id is used to mark different users. The difference is that each request by the browser will contain
Session_id generated by the server.
A Brief Introduction of the process: when the client accesses the server, the server sets the session as needed, stores the session information on the server, and transmits the session_id of the session to the client browser,
The browser saves the session_id in the memory (there are other storage methods, such as writing it in a url), which is called a cookie with no expiration time. After the browser is closed, the cookie is cleared, and no temporary cookie file exists.
In the future, the browser will add this parameter value for each request, and the server will be able to obtain the client data status based on this session_id.
If the browser of the client closes unexpectedly, the session data stored on the server is not immediately released, and the data will still exist. As long as we know the session_id, we can continue to obtain the session information through the request; however, the background session still exists at this time, but the session is saved with an expiration date.
Time. When no client request is received after the specified time, the session is cleared.
The following describes the session storage mechanism. The default session is saved in files, that is, session data is saved as a file. In php, session. save_handler is configured based on php. ini.
To save the session.
Here, by the way, if we want to use server lvs, that is, multiple servers, we generally use the memcached session method. Otherwise, some requests will not be able to find the session.
A simple memcache Configuration:
Session. save_handler = memcache
Session. save_path = "tcp: // 10.28.41.84: 10001"
Of course, if files must be cached, we can make the file nfs and locate all the stored session files in one place.
The session-id returned to the user is stored in the memory. Here we can also set the parameter to save it in the user url.
Official ThinkPHP instructions
01. start the session
02. pause session
03. clear session
04. destroy session
05. get to get the session Value
06. getLocal get private session Value
07. set the session Value
08. setLocal: Set the private session Value
09. name get or set session_name
10. Does is_set set the session value?
11. Does is_setLocal set the private session value?
12. Get or set session_id with id
13. Get or set session_save_path
14. setExpire: Set the session expiration time
15. setCookieDomain: Set a valid Domain Name
16. setCallback sets the callback function for Session Object deserialization.
Example of the most common operation method:
Code: 01. // check whether the Session variable exists
| The Code is as follows: |
Copy code |
|
02. Session: is_set ('name ');
03.
// Assign a value to the Session Variation
04.
Session: set ('name', 'value ');
05.
// Obtain the Session variable
06.
Session: get ('name '); |
Session-related configuration parameters:
Code:
| The Code is as follows: |
Copy code |
|
01. 'session _ name' => 'thinkid', // default Session_name
02.
'Session _ path' => '', // use the default SESSION save PATH
03.
'Session _ type' => 'file', // The default session type supports DB and File
04.
'Session _ EXPIRE '=> '000000', // default SESSION Validity Period
05.
'Session _ table' => 'think _ session', // name of the TABLE in the database SESSION Mode
06.
'Session _ callback' => '', // callback method of the deserialization object |
Note the SESSION_NAME parameter. If you do not want to share the Session value between different projects, set different values. Otherwise, keep the same default value.
If you set the same SESSION_NAME value but want to create a project-based private Session space, what should you do? ThinkPHP also supports private Session operations with the project as the Session space. Taking the previous common operations as an example, we changed the following:
Code:
| The Code is as follows: |
Copy code |
|
01. // check whether the Session variable exists (the current project is valid)
02. Session: is_setLocal ('name ');
03.
// Assign a value to the Session variable (the current project is valid)
04.
Session: setLocal ('name', 'value ');
05.
// Obtain the Session variable (valid for the current project)
06.
Session: getLocal ('name '); |
In this way, it does not conflict with global Session operations and can be used for special situations.
ThinkPHP supports Session operations in the database mode. You can set SESSION_TYPE to DB. If you use the database mode, make sure that the SESSION_TABLE value is set, import the following DDL statements to your database (using MySQL as an example ):
Code:
| The Code is as follows: |
Copy code |
|
01. create table 'think _ session '(
02 .'
Id'int (11) unsigned not null auto_increment,
03 .'
Session_id 'varchar (255) not null,
04 .'
Session_expires 'int (11) not null,
05 .'
Session_data 'blob,
06.
Primary key ('id ')
07 .) |
Note that database connection in Db Session mode uses the project database configuration information for connection. In addition to the database mode, you can also add other Session storage mechanisms, such as the memory mode and Memcache mode. We only need to add the corresponding filter and use the session_set_save_handler method, for specific method definitions, refer to Think. util. filterSessionDb under the Filter. class. php file implementation.
Made a simple login judgment
After logon detection, assign the Session value so that the Session value is false if it is not empty.
| The Code is as follows: |
Copy code |
$ _ SESSION [C ('user _ AUTH_KEY ')] = $ logInFind ['id'];
|
[C ('user _ AUTH_KEY ')] is the built-in method and function class of ThinkPHP. The default value is null when the config. php file is not configured.
Assign the account value retrieved by $ logInFind ['id'] to it. By default, the Session is automatically deleted when the page is closed!
Use the following format to determine other pages
| The Code is as follows: |
Copy code |
If (! Isset ($ _ SESSION [C ('user _ AUTH_KEY ')]) {// isset checks whether a value is assigned to a variable!
$ This-> redirect ('login', 'login'); // go to the registration page
}
|