search
HomeBackend DevelopmentPHP TutorialLook at PHP's session mechanism from two handlers_PHP tutorial

session.save_handler = files

1. session_start()

session_start() is the beginning of the session mechanism. It has a certain probability of turning on 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 based on It is determined by the configuration of php.ini, but 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//过期时间 默认24分钟
            //概率是 session.gc_probability/session.gc_divisor 结果 1/1000, 
            //不建议设置过小,因为session的垃圾回收,是需要检查每个文件是否过期的。
            session.save_path = //好像不同的系统默认不一样,有一种设置是 "N;/path"
            //这是随机分级存储,这个样的话,垃圾回收将不起作用,需要自己写脚本

session will determine whether there is currently $_COOKIE[session_name()]; session_name() returns the COOKIE key value that saves session_id. This value can be found from php.ini session.name = PHPSESSID //Default value PHPSESSID

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 value of COOKIE. It is equivalent to performing the following COOKIE operation. Note that this step performs the setcookie() operation, and COOKIE is in the header Sent in the header, there will be no output before this. PHP has another function session_regenerate_id(). If you use this function, there will be no output before this.

				setcookie(session_name(),
                          session_id(),
                          session.cookie_lifetime,//默认0
                          session.cookie_path,//默认'/'当前程序跟目录下都有效
                          session.cookie_domain,//默认为空
                          )

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 contents of the file, deserialize it, and put it in $_SESSION.

2. Assign value to $_SESSION

For example, add a new value $_SESSION['test'] = 'blah'; then this $_SESSION will only be maintained in memory. When the script execution ends, use the value of $_SESSION to be written to the specified session_id folder, and then close the related resources.

At this stage, it is possible to perform operations to change the session_id, such as destroying an old session_id and generating a new session_id. Half of it is used for custom session operations and role conversion, such as Drupal. Drupal anonymous users have a SESSION Yes, it needs to use a new session_id after logging in.

if (isset($_COOKIE[session_name()])) {
          setcookie(session_name(), '', time() - 42000, '/');//旧session cookie过期
        }
        session_regenerate_id();//这一步会生成新的session_id
       //session_id()返回的是新的值

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. It may already exist, and a new file 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, such as logging out instead of closing the browser, then you need to add it in the code. There are many ways to destroy SESSION:

  • setcookie(session_name(), session_id(), time() - 8000000, ..);//Execute before logging out
  • usset($_SESSION);//This will delete all $_SESSION data. After refreshing, COOKIE is passed, but there is no data.
  • session_destroy();//This function is more thorough, delete $_SESSION, delete the session file, and session_id

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

session.save_handler = user

User-defined session processing mechanism, more intuitive session_set_save_handler('open', 'close', 'read', 'write', 'destroy', 'gc');

session_start(), execute open($save_path, $session_name) to open the session operation handle. $save_path is session.save_path when session.save_handler = files, 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.

The script execution ends, execute write($id, $sess_data) //Two parameters, very simple

If the user needs session_destroy(), execute destroy first and then 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;
      }

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752515.htmlTechArticlesession.save_handler = files 1. session_start() session_start() is the beginning of the session mechanism, it has a certain probability of being turned on Garbage collection, because the session is stored in the file, PHP's own garbage...
Statement
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
What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

What is PDO in PHP?What is PDO in PHP?Apr 28, 2025 pm 04:51 PM

The article discusses PHP Data Objects (PDO), an extension for database access in PHP. It highlights PDO's role in enhancing security through prepared statements and its benefits over MySQLi, including database abstraction and better error handling.

How to create API in PHP?How to create API in PHP?Apr 28, 2025 pm 04:50 PM

Article discusses creating and securing PHP APIs, detailing steps from endpoint definition to performance optimization using frameworks like Laravel and best security practices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!