Session is a very commonly used global variable in php. Now I will introduce some usage summary of php session to beginners. I hope these methods will be helpful to all friends who are new to php. Let’s take a look together. .
The default session storage method of PHP server is file storage. On Windows, the default session server file of PHP is stored in C:/WINDOWS/Temp. Under *NIX, it is stored in /tmp by default. If concurrent access is very difficult, If the file size is too large or too many sessions are created, there will be a large number of session files similar to sess_xxxxxx in these two directories. Too many files in the same directory will lead to performance degradation, and may lead to attacks and ultimately file system errors. For this situation, PHP itself provides a better solution.
Many friends may not have noticed that there is such an item in the Session settings section of php.ini:
; session.save_path = "N; MODE; /path"
This setting allows us to perform multi-level hashing on the session storage directory, where "N" represents the directory level to be set, and "MODE" represents the permission attribute of the directory. The default is 600, which is basically 600 on WINDOWS. It doesn’t need to be set. It doesn’t need to be set on *NIX. The following “/path” indicates the root directory path where the session file is stored. For example, we set it to the following format
session.save_path = "2; /tmp/phpsession"
The above setting means that we use the /tmp/phpsession directory as the root directory to store the PHP session file, and perform two-level directory hashing in this directory. Each level of directory is 0-9 and a-z, a total of 36 alphanumeric characters. is the directory name, so the number of directories for storing sessions can reach 36*36. I believe that this is enough for a single server. If your system architecture is designed to share session data with multiple servers, you can put the directory level Increase to level 3 or more.
It should be noted that php itself will not automatically create subdirectories. You need to create them yourself. The following code for automatically creating directories can be used as a reference. The code below automatically creates level 3 subdirectories, which can be modified as needed.
The code is as follows | 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]); } } } ?> |
Two better solutions are provided below:
1.Session storage
Use the session_set_save_handler function
Function: Customize SESSION storage mechanism.
Can be used to modify the session storage medium, such as logging the session into the database.
Example code
The code is as follows | Copy code | ||||
class sessionsTable extends db{
|
2. Use memcache to store session
Method I: Set globally in php.ini
session.save_handler = memcache
session.save_path = "tcp://127.0.0.1:11211"
Method II: Use ini_set settings in a certain application
ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://127.0.0.1:11211");
When using multiple memcached servers, separate them with commas ",", and as explained in the Memcache::addServer() document, you can take additional parameters "persistent", "weight", "timeout", "retry_interval" " Wait, something like this: "tcp://host1:port1?persistent=1&weight=2,tcp://host2:port2".
1. How to operate session in php:
session_start(); //Use this function to open the session function
$_SESSION //Use predefined global variables to manipulate data
Use unset($_SESSION['key']) //Destroy the value of a session
Easy to operate, everything is implemented by the server; since the processing is in the background, everything also looks safe. But what mechanism does session use, how is it implemented, and how is the session state maintained?
2.session implementation and working principle
The browser and the server use http stateless communication. In order to maintain the state of the client, session is used to achieve this purpose. But how does the server identify different clients or users?
Here we can use an example from life. If you attend a party and meet many people, how will you distinguish different people? You may base it on the face shape or the user’s name
Or a person's ID card, which uses a unique identification. In the session mechanism, such a unique session_id is also used to identify different users. The difference is: the browser will bring
with every request.
The session_id generated for it by the server.
A brief introduction to the process: when the client accesses the server, the server sets the session according to the requirements, saves the session information on the server, and passes the session_id indicating the session to the client browser,
The browser saves this session_id in memory (there are other storage methods, such as writing it in the URL), which we call a cookie without expiration time. After the browser is closed, this cookie will be cleared, and it will not contain the user's temporary cookie file.
In the future, the browser will add this parameter value to every request, and the server can obtain the client's data status based on this session_id.
If the client browser is closed unexpectedly, the session data saved by the server will not be released immediately. The data will still exist at this time. As long as we know the session_id, we can continue to obtain the session information through requests; but at this time, the background session It still exists, but the saved session has an expiration date
time, once there is no client request for more than the specified time, he will clear the session.
The following introduces the session storage mechanism. The default session is saved in files, that is, session data is saved in the form of files. In php, it is mainly based on the configuration of php.ini session.save_handler
to choose how to save the session.
By the way, if we want to make a server LVS, that is, multiple servers, we generally use memcached session, 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 you must use files file caching, we can use nfs to store the files and locate all saved session files in one place.
Just now, the session-id returned to the user is eventually saved in memory. Here we can also set parameters to save it in the user's url.
ThinkPHP official documentation
01.start Start session
02.pause pause session
03.clear clear session
04.destroy destroy session
05.get Get session value
06.getLocal gets the private session value
07.set Set session value
08.setLocal sets private session value
09.name gets or sets session_name
10.is_set whether to set the session value
11.is_setLocal whether to set private session value
12.id Get or set session_id
13.path gets or sets session_save_path
14.setExpire Set session expiration time
15.setCookieDomain sets a valid domain name
16.setCallback sets the callback function when the Session object is deserialized
Examples of the most commonly used operating methods:
Code: 01.// Check whether the Session variable exists
代码如下 | 复制代码 |
02.Session::is_set('name'); 03. |
Configuration parameters related to Session:
Code:
The code is as follows | Copy code | ||||||||
03. 'SESSION_TYPE' = & GT; 'File', // The default session type supports DB and FILE
'SESSION_EXPIRE'=>'300000', // Default Session validity period 05.'SESSION_TABLE'=>'think_session', // Database Session mode table name 06.'SESSION_CALLBACK'=>'', // Callback method for deserialized objects |
代码如下 | 复制代码 |
01.CREATE TABLE `think_session` ( 02. ` |
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 value to Session variable (valid for current project) 04. Session::setLocal('name','value'); 05. // Get Session variables (valid for the current project) 06. Session::getLocal('name'); |
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 the database connection in Db Session mode will use the database configuration information of the project to connect. In addition to the database method, you can also add other methods of Session saving mechanisms, such as memory method, Memcache method, etc. We only need to add the corresponding filter, using the session_set_save_handler method. For the specific method definition, refer to FilterSessionDb under Think.Util.Filter. Implementation of .class.php file.
Created a simple login judgment
After login detection, assign the Session value so that the Session value is either empty or false
代码如下 | 复制代码 |
$_SESSION[C('USER_AUTH_KEY')] = $logInFind['id'] ; |
Where [C('USER_AUTH_KEY')] is ThinkPHP's built-in method and function class. When the config.php file is not configured, it defaults to empty
Give it the account value taken out by $logInFind['id']. By default, the session will be automatically deleted when the page session is closed!
Use the following format to judge other pages
The code is as follows
|
Copy code | ||||
if(!isset($_SESSION[C( 'USER_AUTH_KEY')])) { //isset is to detect whether the variable is assigned a value! |
truehttp: //www.bkjia.com/PHPjc/632699.htmlTechArticlesession is a very commonly used global variable in php. Let me introduce some about php session to beginners. Summary of usage, I hope some methods will be helpful to all beginners who are learning php, next...