Home Backend Development PHP Tutorial How to accurately set session expiration time in php

How to accurately set session expiration time in php

Jun 06, 2018 am 11:15 AM
php session method Expiration

This article mainly introduces the method to accurately set the session expiration time in PHP. Friends who need it can refer to it

In most cases, we use the default setting time for the session expiration time, and For some cases with special requirements, we can set the session expiration time.

For this, you can set php.ini in PHP and find session.gc_maxlifetime = 1440 #(PHP5 defaults to 24 minutes)
Here you can set the expiration time at will. But some people say that after setting it up, it doesn’t seem to work!
In fact, it’s not that it doesn’t work, but because the system defaults:

session.gc_probability = 1
session.gc_pisor = 1000
Copy after login

garbage collection There is a probability, 1/1000 means that the session will be recycled only once in 1000 times.
As long as your access volume is large, you can achieve the recycling effect.
Or you can also set the value of session.gc_pisor,
For example: session.gc_pisor = 1 , so that you can clearly see the effect of SESSION expiration.

The most commonly used setting is in the php program, as shown in the following example program:

<?php
if(!isset($_SESSION[&#39;last_access&#39;])||(time()-$_SESSION[&#39;last_access&#39;])>60)
$_SESSION[&#39;last_access&#39;] = time();
?>
Copy after login

That’s it. If you want to set the expired value, you can also do it in the program:

<?php
unset($_SESSION[&#39;last_access&#39;]);// 或 $_SESSION[&#39;last_access&#39;]=&#39;&#39;;
?>
Copy after login

session There is an expiration mechanism:

session.gc_maxlifetime It turns out that session expiration is a small probability event. Session.gc_probability and session.gc_pisor are used to determine the probability of running gc in the session. session.gc_probability and session. The default values ​​of gc_pisor are 1 and 100 respectively. are the numerator and denominator respectively, so the probability of gc running in the session is 1%. If you modify these two values, it will reduce the efficiency of PHP. So this approach is wrong! !
Therefore, modifying the gc_maxlifetime variable in the php.ini file can extend the session expiration time: (for example, we modify the expiration time to 86400 seconds)
session.gc_maxlifetime = 86400
Then, restart you A web service (usually apache) will do.

When session "recycling" occurs:

By default, for every php request, there will be a 1/100 probability of recycling, so it may be simple Understood as "one recycling occurs every 100 php requests". This probability is controlled by the following parameters
#The probability is gc_probability/gc_pisor

session.gc_probability = 1
session.gc_pisor = 100
Copy after login

Note 1:Assume that in this case gc_maxlifetime=120, If a session file was last modified 120 seconds ago, the session will still be valid until the next recycling (1/100 probability) occurs.

Note 2: If your session uses session.save_path to save the session elsewhere, the session recycling mechanism may not automatically process expired session files. At this time, you need to delete expired sessions manually (or crontab) on a regular basis:

cd /path/to/sessions; find -cmin +24 | xargs rm
Copy after login

The session in PHP never expires

Not modifying the program is the best way, because if you modify the program, the testing department will be very depressed, so you can only modify the system environment configuration. In fact, it is very simple. Open the php.ini setting file and modify The three lines are as follows:

1. session.use_cookies

Set this value to 1 and use cookies to pass sessionid

2 , 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 is because of this that the PHP session cannot be used permanently! So let's set it to a number we think is big, how about 999999999, that's ok! that's all.

3. 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! So let's also set it to 99999999.

That's it, everything is ok. Of course, if you don't believe it, just test it and see - set up a session and come back after 10 days and a half to see if your computer is not powered off or down. , you can still see the sessionid.

Of course, it is also possible that you do not have the authority to control the server and are not as lucky as me to be able to modify the php.ini settings. We have ways to rely on ourselves. Of course, we must use the client to store cookies. The obtained sessionID is stored in the client's cookie, sets the value of this cookie, and then passes this value to the session_id() function. The specific method is as follows:

<?php
session_start(); // 启动Session 
$_SESSION[&#39;count&#39;]; // 注册Session变量Count 
isset($PHPSESSID)?session_id($PHPSESSID):$PHPSESSID = session_id(); 
// 如果设置了$PHPSESSID,就将SessionID赋值为$PHPSESSID,否则生成SessionID 
$_SESSION[&#39;count&#39;]++; // 变量count加1 
setcookie(&#39;PHPSESSID&#39;, $PHPSESSID, time()+3156000); // 储存SessionID到Cookie中 
echo $count; // 显示Session变量count的值 
?>
Copy after login

Session failure is not delivered

我们先写个php文件:, 传到服务器去看看服务器的参数配置。
转到session部分,看到session.use_trans_sid参数被设为了零。
这个参数指定了是否启用透明SID支持,即session是否随着URL传递。我个人的理解是,一旦这个参数被设为0,那么每个URL都会启一个session。这样后面页面就无法追踪得到前面一个页面的session,也就是我们所说的无法传递。两个页面在服务器端生成了两个session文件,且无关联。(此处精确原理有待确认)
所以一个办法是在配置文件php.ini里把session.use_trans_sid的值改成1。

当然我们知道,不是谁都有权限去改php的配置的,那么还有什么间接的解决办法呢?
下面就用两个实例来说明:
文件1 test1.php

<?php
//表明是使用用户ID为标识的session
session_id(SID);
//启动session
session_start();
//将session的name赋值为Havi
$_SESSION[&#39;name&#39;]="Havi";
//输出session,并设置超链接到第二页test2.php
echo "<a href="test2.php" rel="external nofollow" >".$_SESSION[&#39;name&#39;]."</a>";
?>
Copy after login

文件2: test2.php

<?php
表明是使用用户ID为标识的session
session_id(SID);
//启动session
session_start();
//输出test1.php中传递的session。
echo "This is ".$_SESSION[&#39;name&#39;];
?>
Copy after login

所以,重点是在session_start();前加上session_id(SID);,这样页面转换时,服务器使用的是用户保存在服务器session文件夹里的session,解决了传递的问题。
不过有朋友会反映说,这样一来,多个用户的session写在一个SID里了,那Session的价值就发挥不出来了。所以还有一招来解决此问题,不用加session_id(SID);前提是你对服务器的php.ini有配置的权限:
output_buffering改成ON,道理就不表了。
第二个可能的原因是对服务器保存session的文件夹没有读取的权限,还是回到phpinfo.php中,查看session保存的地址:

session.save_path: var/tmp
Copy after login

所以就是检查下var/tmp文件夹是否可写。
写一个文件:test3.php来测试一下:

<?php
echo var_dump(is_writeable(ini_get("session.save_path")));
?>
Copy after login

如果返回bool(false),证明文件夹写权限被限制了,那就换个文件夹咯,在你编写的网页里加入:

//设置当前目录下session子文件夹为session保存路径。
$sessSavePath = dirname(__FILE__).&#39;/session/&#39;;
//如果新路径可读可写(可通过FTP上变更文件夹属性为777实现),则让该路径生效。
if(is_writeable($sessSavePath) && is_readable($sessSavePath))
{
session_save_path($sessSavePath);
}
Copy after login

相关推荐:

PHP 中cookie 和session的联系以及session配置

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

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles