Some usages of session in PHP in session and thinkphp

Source: Internet
Author: User
Tags hash ini memcached php file php server php session table name valid

PHP server-side default session storage is the way in which files are stored, and on WINDOWS, PHP's default sessions server file is stored under C:/windows/temp, *nix under the default storage in/TMP, If concurrent access is large or the session is set up too much, there will be a large number of sessions files similar to sess_xxxxxx in both directories, with too many files in the same directory that can degrade performance and may result in an attack resulting in file system errors. In this case, the PHP body provides a better solution.
Many friends may not have noticed this in the session setup section of PHP.ini:
; Session.save_path = "N; MODE; /path "

This setting provides us with a multilevel hash of the session storage directory. Where "N" represents the directory progression to be set, "MODE" indicates the permissions attribute of the directory, the default is 600, the basic is not set on Windows, *nix can not be set, the back of the "/path" Represents the root directory path for the session file, such as the format we set to the following

Session.save_path = "2; /tmp/phpsession "

The above setting indicates that we put the/tmp/phpsession directory as the PHP session file for the root directory, in the directory for the two-level directory hash, each level directory is 0-9 and a-Z a total of 36 alphanumeric directory name, so that the table of contents of the session can reach 36 * 36, believe that as a single server, this is fully enough, if your system architecture designed for multiple servers sharing session data, you can add directory level to level 3 or more.

Note that PHP itself does not automatically create subdirectories, you need to create your own, the following automatically create the directory code, we can make a reference. The following code automatically creates a level 3 subdirectory that you can modify yourself to suit your needs.

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

}

}

}

?>

There are two better solutions available:
1.session Storage

Using the Session_set_save_handler function

Role: Customize the session storage mechanism.

Can be used to modify the session storage media, such as the session warehousing and other 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} ') ' 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");

The use of multiple memcached servers is separated by commas "," and as described in the Memcache::addserver () document, with additional parameters such as "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

Destroys the value of a session using unset ($_session[' key ')]/

Simple operation, everything is implemented by the server, because the processing in the background, everything looks very safe. But what kind of mechanism does the session adopt, and how is it implemented, and how to maintain the state of the conversation?

2.session implementation and working principle

The browser and server use HTTP stateless communication, in order to maintain the state of the client, using session to achieve this goal. But how does the service end label different clients or users?
Here we can use an example of life, if you attend a party, know a lot of people, you will take the way to distinguish between different people! You may be depending on the face shape, or depending on the user's name,
Or a person's identity card, a unique logo is used. In the session mechanism, a unique session_id is also used to mark different users, except that each request from the browser will take
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 marks the sessions to the client browser.
The browser saves the session_id in memory (and other storage methods, such as in the URL), which we call a cookie with no expiration time. When the browser is closed, the cookie is cleared, and it does not have a user's cookie temp file.
After the browser each request will be added this parameter value, and then the server according to this session_id, can obtain the client data state.

If the client browser shuts down unexpectedly, the server saves session data is not immediately released, the data will still exist, as long as we know the session_id, we can continue to obtain this session by request information; But this time backstage session still exists, But the session save has an expiration
Time, once there is no client request for more than the specified time, he clears the session.

The following is an introduction to the session storage mechanism, the default session is saved in files, that is, to save the session data as a file. In PHP, mainly according to the php.ini configuration Session.save_handler
To choose how 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 of session, otherwise it will cause some requests can not find sessions.
A simple memcache configuration:
Session.save_handler = memcache
Session.save_path = "tcp://10.28.41.84:10001"

Of course, if you have to use the files file cache, we can make the file NFS, all the save session files to a location.

Just now the Session-id returned to the user is eventually saved in memory, where we can also set the parameters to save it in the user's URL.

thinkphp Official Documentation

01.start Start session

02.pause Pause Session
03.clear Erase Session
04.destroy Destroy session
05.get Get Session value
06.getLocal Get Private Session value
07.set Setting Session Value
08.setLocal Set 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 values
12.id Get or set session_id
13.path Get or set Session_save_path
14.setExpire Setting session Expiration Time
15.setCookieDomain set a valid domain name
16.setCallback set callback function for session object deserialization
Examples of the most common methods of action:

Code: 01.//detects if the session variable exists

The code is as follows Copy Code

02.session::is_set (' name ');

03.
Assigning values to session variables
04.
Session::set (' name ', ' value ');
05.
Get Session variable
06.
Session::get (' name ');

Configuration parameters related to session:

Code:

The code is as follows Copy Code

' 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 Way table name
06.
' Session_callback ' => ',//deserialization of the object's callback method

Where the Session_name parameter requires attention, if you need to not share the value of the delivery session between different items, set a different value, or leave the same default value.
If you set the same Session_name value, but you want to create a private session space based on your project, what should you do with it? Thinkphp also supports private session operations with project as session space, taking the previous common operations for example, we change the following:

Code:

The code is as follows Copy Code

01.//detect if Session variable exists (current project is active)
02.session::is_setlocal (' name ');

03.
Assign a value to a session variable (current project is valid)
04.
Session::setlocal (' name ', ' value ');
05.
Get Session variable (current project valid)
06.
Session::getlocal (' name ');

This will not conflict with the global session operation and can be used for special situations.

thinkphp Support Database mode of session operation, set Session_type value of DB on it, if you use the database method, but also to ensure that the value of session_table set, and import the following DDL to your Database (in MySQL for 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) Not NULL,
04. '
Session_expires ' int (one) not NULL,
05. '
Session_data ' blob,
06.
PRIMARY KEY (' id ')
07.)

Note that the DB session database connection is connected using the project's database configuration information. In addition to the database method, can also add other ways of the session save mechanism, such as memory mode, memcache way, etc., we just add the appropriate filter on the line, using the Session_set_save_handler method, The specific method defines the reference Think.Util.Filter the implementation of the FilterSessionDb.class.php file below.

Made a simple landing judgment

The session value is given after the login detection so that the value of the session is non-null false

The code is as follows Copy Code
$_session[c (' User_auth_key ')] = $logInFind [' id '];

where [C (' User_auth_key ')] is the thinkphp built-in method and function class. Null defaults when config.php files are not configured
The $loginfind[' ID ' is taken out of the account value assigned to it, the default is to close the page session automatically deleted disappear!

Other pages use the following format to judge

  code is as follows copy code
if (!isset Session[c (' User_auth_key ')]) { //isset is to detect whether the variable is assigned!
     $this->redirect (' Login ', ' Login '); Go to registration page
   }

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.