search
HomeBackend DevelopmentPHP ProblemHow to set expiration time in php

php method to set expiration time: first set the session and read the session; then clear the session through "unset($_SESSION[$name]);"; finally output "session::get('test') ;" has expired.

How to set expiration time in php

Recommended: "PHP Video Tutorial"

Strictly set the session expiration time in php!

Strictly limit session expiration after 30 minutes!

1. Set the lifetime of the client cookie to 30 minutes;

2. Set the maximum lifetime of the session to 30 minutes;

3. For each session value Add a timestamp, and then make a judgment when the program is called;

As for why, let’s first understand the basic principles of session in PHP:

The default session validity period in PHP is 1440 seconds (24 minutes), that is to say, if the client does not refresh for more than 24 minutes, the current session will become invalid. Of course, if the user closes the browser, the session will end and the Session will naturally no longer exist!

As we all know, the Session is stored on the server side. The user's file is obtained based on the SessionID provided by the client, and then the file is read to obtain the value of the variable. The SessionID can use the client's Cookie or the Http1.1 protocol.

Query_String (the part after the "?" of the accessed URL) is sent to the server, and then the server reads the directory of the Session...

To control the life cycle of the Session, first we need to Learn about the relevant settings of php.ini about Session (open the php.ini file, in the "[Session]" section):

1. session.use_cookies: The default value is "1", which means SessionID uses Cookies. To pass, otherwise use Query_String to pass;

2. session.name: This is the variable name stored in SessionID, which may be Cookie or Query_String. The default value is "PHPSESSID";

3. session.cookie_lifetime: This represents the time the SessionID is stored in the client cookie. The default is 0, which means that the SessionID will be invalidated as soon as the browser closes it... It is because of this that the Session cannot be used permanently!

4. session.gc_maxlifetime: This is the time that Session data is stored on the server side. If this time is exceeded, the Session data will be automatically deleted!

There are many more settings, but these are the ones related to this article. Let’s start with how to set the Session survival period.

As mentioned before, the server reads Session data through SessionID, but generally the SessionID sent by the browser is gone after the browser is closed, so we only need to manually set the SessionID and save it, isn't it? Yes...

If you have the operating authority of the server, then setting this is very, very simple. You just need to perform the following steps:

1. Set "session.use_cookies" to 1, Use Cookie to store SessionID, but the default is 1, generally no need to modify;

2. Change "session.cookie_lifetime" to the time you need to set (for example, one hour, you can set it to 3600, in seconds Unit);

3. Set "session.gc_maxlifetime" to the same time as "session.cookie_lifetime";

It is clearly stated in the PHP documentation that the parameters for setting the session validity period are session.gc_maxlifetime. This parameter can be modified in the php.ini file or through the ini_set() function. The problem is that after many tests, modifying this

parameter basically has no effect, and the session validity period still maintains the default value of 24 minutes.

Due to the working mechanism of PHP, it does not have a daemon thread to regularly scan session information and determine whether it is invalid. When a valid request occurs, PHP will decide whether to start a GC ( Garbage Collector).

By default, session.gc_probability = 1, session.gc_divisor = 100, which means there is a 1% probability that GC will be started. The job of the GC is to scan all session information, subtract the last modified date of the session from the current time, and compare it with the session.gc_maxlifetime parameter. If the survival time has exceeded gc_maxlifetime, then The session is deleted.

So far, everything is working normally. So why does gc_maxlifetime become invalid?

By default, session information will be saved in the system's temporary file directory in the form of text files. Under Linux, this path is usually \\tmp, and under Windows it is usually C:\\Windows\\Temp. When there are multiple PHP applications on the server, they will save their session files in the same directory. Similarly, these PHP applications will also start GC at a certain probability and scan all session files.

The problem is that when GC is working, it does not distinguish between sessions on different sites. For example, site A's gc_maxlifetime is set to 2 hours, and site B's gc_maxlifetime is set to the default 24 minutes. When site B's GC starts, it scans

Scan the public temporary file directory and delete all session files older than 24 minutes, regardless of whether they come from site A or B. In this way, the gc_maxlifetime setting of site A is useless.

Once you find the problem, it’s easy to solve it. Modify the session.save_path parameter, or use the session_save_path() function to point the directory where the session is saved to a dedicated directory. The gc_maxlifetime parameter works normally.

Another problem is that gc_maxlifetime can only guarantee the shortest time for the session to survive, and cannot be saved. After this time, the session information will be deleted immediately. Because GC is started based on probability, it may not be started for a long period of time, so a large number of sessions will still be valid after exceeding gc_maxlifetime.

One way to solve this problem is to increase the probability of session.gc_probability/session.gc_divisor. If mentioned to 100%, this problem will be completely solved, but it will obviously have a serious impact on performance. Another method is to

only use PHP to implement it, create a session class, and write the expiration time when the session is written. When reading, determine whether it has expired based on the expiration time.

class Session{  
      
        /** 
         * 设置session 
         * @param String $name   session name 
         * @param Mixed  $data   session data 
         * @param Int    $expire 超时时间(秒) 
         */  
        public static function set($name, $data, $expire=600){  
            $session_data = array();  
            $session_data['data'] = $data;  
            $session_data['expire'] = time()+$expire;  
            $_SESSION[$name] = $session_data;  
        }  
      
        /** 
         * 读取session 
         * @param  String $name  session name 
         * @return Mixed 
         */  
        public static function get($name){  
            if(isset($_SESSION[$name])){  
                if($_SESSION[$name]['expire']>time()){  
                    return $_SESSION[$name]['data'];  
                }else{  
                    self::clear($name);  
                }  
            }  
            return false;  
        }  
      
        /** 
         * 清除session 
         * @param  String  $name  session name 
         */  
        private static function clear($name){  
            unset($_SESSION[$name]);  
        }  
      
    }  
    demo.php  
      
    session_start();  
      
    $data = '123456';  
    session::set('test', $data, 10);  
    echo session::get('test'); // 未过期,输出  
    sleep(10);  
    echo session::get('test'); // 已过期

The above is the detailed content of How to set expiration time in php. For more information, please follow other related articles on the PHP Chinese website!

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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft