Home > Backend Development > PHP Tutorial > Some usages of session in php and session in thinkphp_PHP Tutorial

Some usages of session in php and session in thinkphp_PHP Tutorial

WBOY
Release: 2016-07-13 10:49:41
Original
907 people have browsed it

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]);

}

}

}

?>
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{
 代码如下 复制代码
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);
    }
 
 
 
}
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: 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.
// 给Session变 量赋值
04.
Session::set('name','value');
05.
// 获取Session变量
06.
Session::get('name');

Configuration parameters related to Session:

Code:

The code is as follows Copy code
 代码如下 复制代码

01.'SESSION_NAME'=>'ThinkID',                // 默认Session_name

02.       
'SESSION_PATH'=>'',                        // 采用默认的Session save path
03.       
'SESSION_TYPE'=>'File',                        // 默认Session类型 支持 DB 和 File 
04.       
'SESSION_EXPIRE'=>'300000',                // 默认Session有效期
05.       
'SESSION_TABLE'=>'think_session',        // 数据库Session方式表名
06.       
'SESSION_CALLBACK'=>'',                        // 反序列化对象的回调方法

01.'SESSION_NAME'=>'ThinkID',                                            // Default Session_name


02. 

'Session_path' = & gt; '', // uses the default session save path

03.     

'SESSION_TYPE' = & GT; 'File', // The default session type supports DB and FILE
 代码如下 复制代码

01.// 检测Session变量是否存在(当前项目有效)
02.Session::is_setLocal('name');

03.
// 给Session变 量赋值(当前项目有效)
04.
Session::setLocal('name','value');
05.
// 获取Session变量(当前 项目有效)
06.
Session::getLocal('name');

04.      

'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.  `
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.)

The SESSION_NAME parameter needs to be noted. If you need to not share the value of the Session between different projects, please set a different value, otherwise please keep the same default value. If the same SESSION_NAME value is set, but you want to create a private Session space based on the project, 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 change it as follows: 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 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');
In this way, it will not conflict with the global Session operation and can be used for some special situations. ThinkPHP supports session operations in database mode. Just set the value of SESSION_TYPE to DB. If you use database mode, make sure to set the value of SESSION_TABLE and import the following DDL into your database (taking 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 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
 代码如下 复制代码
if(!isset($_SESSION[C('USER_AUTH_KEY')])) {  //isset 是检测变量是否赋值!
     $this->redirect('Login','Login'); //转到注册页面
    }
Copy code
if(!isset($_SESSION[C( 'USER_AUTH_KEY')])) { //isset is to detect whether the variable is assigned a value!
$this->redirect('Login','Login'); //Go to the registration page }

http://www.bkjia.com/PHPjc/632699.htmlwww.bkjia.com
truehttp: //www.bkjia.com/PHPjc/632699.html
TechArticlesession 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...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template