Home > Backend Development > PHP Tutorial > Some basic knowledge of session in php_PHP tutorial

Some basic knowledge of session in php_PHP tutorial

WBOY
Release: 2016-07-13 10:50:17
Original
823 people have browsed it

In PHP, session is a server global variable that can be passed between pages, so session is often used for server-side user member login verification. The security of session is also very high. Let me introduce the basic knowledge about PHP session. .

What do you think of session? I don’t know if you have studied it. Today, Danai’s PHP training teacher wants to share some content about this with you. I hope you will like it.

What is the life cycle of a session

1 When the browser ends, its life cycle also ends, but the file still exists in /tmp/(sess_???)

2 The session ID will be reassigned the next time you reopen the browser. If you use session_id() to bring back the previous ID, it will read the sess_??? that remains in /tmp and retrieve all your previous settings. Parameters

3 You can modify the remaining time of the session file in PHP.ini

session.gc_maxlifetime = 1440; after this number of seconds, stored
data will be seen as 'garbage' and
​cleaned up by the gc process
The default is 1440 seconds, 24 minutes

Note on storage path issues when using session

Take a look at the session settings in php.ini

[Session]
session.save_handler = files; handler used to store/retrieve data
session.save_path = /tmp ; argument passed to save_handler
​in the case of files, this is the
path where data files are stored

By default, it is stored in the /tmp directory. This directory may not necessarily exist! ! ! It is best to change it to your php installation path, such as c:/php


Thoroughly understand PHP’s SESSION mechanism 1.session.save_handler = files

* 1. session_start()
​​​​ 1. session_start() is the start of the session mechanism. It has a certain probability of starting garbage collection because the session is stored in a file,
PHP's own garbage collection is invalid. SESSION recycling requires deleting files. This probability is determined by the configuration of php.ini,
However, some systems have session.gc_probability = 0, which means the probability is 0, and garbage collection is implemented through cron scripts.

session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440 //Expiration time default 24 minutes
//The probability is session.gc_probability/session.gc_divisor result 1/1000,
                     // It is not recommended to set it too small, because the garbage collection of the session needs to check whether each file has expired.
session.save_path = //It seems that different systems have different default settings. One setting is "N;/path"
//This is random hierarchical storage. In this case, garbage collection will not work and you need to write your own script

2. The session will determine whether there is currently $_COOKIE[session_name()]; session_name() returns the COOKIE key value that saves the session_id,
This value can be found from php.ini

session.name = PHPSESSID //Default value PHPSESSID
                                                                     

3. If it does not exist, a session_id will be generated, and then the generated session_id will be passed to the client as the COOKIE value.

It is equivalent to executing the following COOKIE operation. Note that this step executes the setcookie() operation, and the COOKIE is sent in the header,
There is no output before this. PHP has another function session_regenerate_id(). If you use this function, there is no output before this.

setcookie(session_name(),
session_id(),
session.cookie_lifetime,//Default 0
session.cookie_path, //The default '/' is valid in the current program and directory
session.cookie_domain,//Default is empty
)

4. If it exists then session_id = $_COOKIE[session_name];
                   Then go to the folder specified by session.save_path to find the file named 'SESS_'. session_id().
                                                                                                                                                                                                      Read the content of the file, deserialize it, and then put it into $_SESSION
* 2. Assign value to $_SESSION
For example, if you add a new value $_SESSION['test'] = 'blah'; then this $_SESSION will only be maintained in memory. When the script execution ends,
Use to write the value of $_SESSION to the folder specified by session_id, and then close the related resources. It is possible to change the session_id at this stage,
For example, destroy an old session_id and generate a new session_id. Half of it is used for custom session operations and role conversion,
For example, Drupal. Drupal's anonymous user has a SESSION. When it logs in, it needs to use a new session_id

if (isset($_COOKIE[session_name()])) {
              setcookie(session_name(), '', time() - 42000, '/');//Old session cookie expires
}
session_regenerate_id();//This step will generate a new session_id
​​​ //session_id() returns the new value

3. Write SESSION operation
At the end of the script, the SESSION write operation will be performed, and the value in $_SESSION will be written to the file named by session_id, which may already exist,
New files may need to be created.
* 4. Destroy SESSION
The COOKIE sent by SESSION is generally an instant COOKIE and is stored in memory. It will expire when the browser is closed. If you need to force the expiration manually,
For example, to log out instead of closing the browser, you need to destroy the SESSION in the code. There are many methods,
o 1. setcookie(session_name(), session_id(), time() - 8000000, ..);//Execute before logging out
                o 2. usset($_SESSION);//This will delete all $_SESSION data. After refreshing, COOKIE is passed, but there is no data.
                  o 3. session_destroy();//This function is more thorough, delete $_SESSION, delete the session file, and session_id

When refreshing again without closing the browser, COOKIES will be sent to 2 and 3, but the data cannot be found

2.session.save_handler = user

User-defined session processing mechanism, more intuitive
* session_set_save_handler('open', 'close', 'read', 'write', 'destroy', 'gc');
1.session_start(),
Execute open($save_path, $session_name) to open the session operation handle
        $save_path In the case of session.save_handler = files, it is session.save_path,
But if the user customizes it, neither of these two parameters will be used, and TRUE will be returned directly

Execute read($id) to read data from it.//This parameter is automatically passed to session_id(), and you can operate through this value.
* 2. Script execution ends
Execute write($id, $sess_data) //Two parameters, very simple
* 3. If the user needs session_destroy()
Execute destroy first. Then execute step 2

A practical example:

 代码如下 复制代码

      //SESSION初始化的时候调用
      function open($save_path, $session_name)
      {
        global $sess_save_path;
        $sess_save_path = $save_path;
        return(true);
      }

      //关闭的时候调用
      function close()
      {
        return(true);
      }

      function read($id)
      {
        global $sess_save_path;
        $sess_file = "$sess_save_path/sess_$id";
        return (string) @file_get_contents($sess_file);
      }
      //脚本执行结束之前,执行写入操作
      function write($id, $sess_data)
      {
        echo "sdfsf";
        global $sess_save_path;

        $sess_file = "$sess_save_path/sess_$id";
        if ($fp = @fopen($sess_file, "w")) {
          $return = fwrite($fp, $sess_data);
          fclose($fp);
          return $return;
        } else {
          return(false);
        }

      }

      function destroy($id)
      {
        global $sess_save_path;

        $sess_file = "$sess_save_path/sess_$id";
        return(@unlink($sess_file));
      }

      function gc($maxlifetime)
      {
        global $sess_save_path;

        foreach (glob("$sess_save_path/sess_*") as $filename) {
          if (filemtime($filename) + $maxlifetime < time()) {
@unlink($filename);
}
}
return true;
}


Example

PHP Session Before you store user information in a PHP session, you must first start the session.

Note: The session_start() function must be placed before the tag:

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

php session_start(); ?>



<🎜>php session_start(); ?>

The above code will register the user's session with the server so that you can start saving user information, and will assign a UID to the user's session.
Store Session variables
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

// store session data $_SESSION['views']=1;
The code is as follows
 代码如下 复制代码

session_start();
// store session data
$_SESSION['views']=1;
?>


//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>


Copy code

session_start();

?>

//retrieve session data echo "Pageviews=". $_SESSION['views']; ?>
Output: Pageviews=1
http://www.bkjia.com/PHPjc/632652.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632652.htmlTechArticleIn php, session is a server global variable that can be passed between pages, so session is often used by server-side users Member login verification and session security are also very high...
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