Why does php Session have no effect?
Session is a very important data storage variable in development. It can realize value transfer between different pages. Let’s introduce it to you below. When using Session, you may encounter some expired and invalid problems. Friends who need it can refer to
php Session invalid analysis
During the PHP development process, some friends may often You will encounter the problem that the files generated by the Session cannot be automatically cleared. In fact, it is not really impossible to clear, but there is a probability problem. As long as the number of visits to your site is large enough, those files can be automatically cleared. If the number of visits is relatively small and the files are not pleasing to the eye, you can realize the automatic clearing function of Session files by configuring it in php.ini. The specific configuration is as follows:
Find
session.gc_probability = 1
session.gc_pisor = 1000
The above two parameters are actually this probability. By default, it is 1/1000
Change session.gc_pisor = 1000 to session.gc_pisor = 100
If you want to achieve complete real-time, you can change this parameter to 1, so the probability is 100%
Related topic recommendations: php session (including pictures, texts, videos, cases)
See how session works
Overview: Every PHP request has a 1/100 probability (default value) of triggering "session recycling". If "session recycling" occurs, the /tmp/sess_* files will be checked. If the last modification time exceeds 1440 seconds (the value of gc_maxlifetime), they will be deleted, which means that these sessions have expired.
1. How does session exist on the server side (usually Apache with PHP module)?
By default, PHP will save the session in the /tmp directory, and the file name will be like this: sess_01aab840166fd1dc253e3b4a3f0b8381. Each file corresponds to a session.
more /tmp/sess_01aab840166fd1dc253e3b4a3f0b8381 username|s:9:”jiangfeng”;admin|s:1:”0〃;
#Variable name|Type: length: value
Deleting the session file here means that the corresponding session is invalid.
2. How does session exist on the client side (usually the browser)?
session On the browser side, you only need to save the session ID (the unique ID generated by the server side). There are two ways to save it: in cookies and in URLs. If the session ID is saved in the cookie, you can see that there is a PHPSESID variable in the browser's cookie. If it is passed by URL, you can see the URL in the form:
index.php?PHPSESID=01aab840166fd1dc253e3b4a3f0b8381. (On the server side, use session.use_cookies to control which method is used)
3. On the server side, how does PHP determine whether the session file has expired?
If the "last modification time" to "now" exceeds gc_maxlifetime (default is 1440) seconds, this session file is considered expired. When the next session is recycled, if this file If it still has not been changed, the session file will be deleted (the session will expire).
Simply put, if I log in to a website and there is no operation within 1440 seconds (default value), then the corresponding session is considered to have expired.
So, 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, just restart your web service (usually apache).
Note: In php5, session expiration uses a recycling mechanism. The time set here is 86400 seconds. If the session has not been modified within 86400 seconds, it will not be deleted until the next "recycling".
4. When does session "recycling" occur?
By default, for every PHP request, there will be a 1/100 probability of recycling, so it may be simply understood as "one recycling occurs for 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
Note 1: Assume that in this case gc_maxlifetime=120, if a session file was last modified 120 seconds ago, then the session will still be valid before 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) regularly:
cd /path/to/sessions; find -cmin +24 | xargs rm
5. Some special circumstances
因为回收机制会检查文件的“最后修改时间”,所以如果某个会话是活跃的,但是session的内容没有改变过,那么对应的session文件也就没有改变过,回收机制会认为这是一个长时间没有活跃的session而将其删除。这是我们不愿看到的,可以通过增加如下的简单代码解决这个问题:
<?php if(!isset($_SESSION['last_access'])||(time()-$_SESSION['last_access'])>60) $_SESSION['last_access'] = time(); ?>
代码会每隔60秒,尝试修改修改一次session。
总结:如果想修改session过期时间,修改变量gc_maxlifetime就可以了。php5的session采用被动的回收机制(garbage collection)。过期的session文件不会自己消失,而是通过触发“回收”来处理过期的session。
我们下面来详细看看一些其它的设置session时间的问题
Session 过期时间参数
设定过期时间参数, 主要是设定 session.gc_maxlifetime 的参数即可, 再保险一点的设定, 就设定下面这两个参数.
ini_set('session.cookie_lifetime', 0); // 可用 print_r(session_get_cookie_params()); 观察 ini_set('session.gc_maxlifetime', 3600); // 可用 echo ini_get("session.gc_maxlifetime"); 观察
session_cookie_lifetime 设为 0 的话, 代表等到 browser 才把此 cookie 清掉.(session 和 browser cookie 是有相关的)
如果懒得想这些, 直接用下面的 function 就可以了
Session 过期时间程式
<?php function start_session($expire = 0) { if ($expire == 0) { $expire = ini_get('session.gc_maxlifetime'); } else { ini_set('session.gc_maxlifetime', $expire); } if (empty($_COOKIE['PHPSESSID'])) { session_set_cookie_params($expire); session_start(); } else { session_start(); setcookie('PHPSESSID', session_id(), time() + $expire); } } ?>
使用方式
于程式最上方加入: start_session(600); // 代表 600 秒后会过期 (取代原本 session_start())
如果要再延长过期时间, 只要再做修改即可.
但是有个问题要注意, 就是 PHP 的 session 预设是存成 file, 所以 /tmp 可能会因这样设定而爆掉(档案太多), 通常解法是把 session 存进 DB/memcache 中.
相关学习推荐:PHP编程从入门到精通
The above is the detailed content of Why does php Session have no effect?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Coinbase Security Login Guide: How to Avoid Phishing Sites and Scams? Phishing and scams are becoming increasingly rampant, and it is crucial to securely access the Coinbase official login portal. This article provides practical guides to help users securely find and use the latest official login portal of Coinbase to protect the security of digital assets. We will cover how to identify phishing sites, and how to log in securely through official websites, mobile apps or trusted third-party platforms, and provide suggestions for enhancing account security, such as using a strong password and enabling two-factor verification. To avoid asset losses due to incorrect login, be sure to read this article carefully!

This article details how to register an account on the official website of Ouyi OKX Exchange and start cryptocurrency trading. As the world's leading cryptocurrency exchange, Ouyi provides a wide range of trading varieties, multiple trading methods and strong security guarantees, and supports convenient withdrawal of a variety of fiat and cryptocurrencies. The article covers the search methods for Ouyi official website registration entrance, detailed registration steps (including email/mobile registration, information filling, verification code verification, etc.), as well as precautions after registration (KYC certification, security settings, etc.), and answers common questions to help novice users quickly and safely complete Ouyi account registration and start a cryptocurrency investment journey.

In digital currency transactions, security is crucial. Due to the prevalence of phishing, it is crucial to find Ouyi OKX official entrance address and official links. Incorrect links can lead to account theft, asset loss and identity theft. This article will provide a comprehensive guide to secure access to the Ouyi OKX official platform, helping users identify and avoid phishing websites and protecting the security of digital assets. We will introduce how to confirm the official portal of Ouyi OKX through official websites, official applications, official social media accounts and other trusted channels, and provide important security tips, such as avoiding unknown links, using strong passwords and enabling two-factor verification, to ensure your transactions are safe and reliable.

As a veteran cryptocurrency derivatives trading platform, the accuracy of its official website entrance is crucial. Due to rampant phishing websites, misent entry into fake websites can lead to account theft and loss of funds. This article aims to guide users to safely access the BitMEX official website, provide various methods such as trusted cryptocurrency information platforms (such as CoinMarketCap, CoinGecko), official social media, verification of existing addresses and official support channels, and emphasizes the use of security measures such as two-factor verification, regular password changes and use of security software to help users effectively avoid risks and ensure account security.

With the increasing popularity of digital currency trading, it is crucial to choose a safe and reliable trading platform. As the world's leading digital asset exchange, OKX's security has attracted much attention. However, many phishing websites impersonate OKX official, causing users to face the risks of account security and asset losses. This article will explain in detail how to identify and access the real Ouyi OKX official website and APP entrance to avoid phishing website traps and ensure the security of your digital assets. Through various channels such as official website verification, official app download, official social media channels, and official customer service consultation, you can effectively identify and access the OKX official platform to ensure the security of your transactions. Please be sure to carefully check the domain name, check the HTTPS protocol, and improve network security awareness.

Simulated transactions, also known as simulated disks or virtual transactions, are an excellent way to learn and practice cryptocurrency trading, allowing users to trade with virtual funds without taking any actual financial risks. By simulated trading, you can learn trading platform operations at zero risk, test trading strategies, practice emotional control, and become familiar with leverage use. Exchanges such as Binance, Ouyi, and Sesame Open Door all provide simulated trading platforms, and software such as TradingView and MetaTrader also provide similar functions. Although simulated trading can effectively improve trading skills, you should pay attention to the differences between them and real trading, and be cautious and do not overconfidence. This article will introduce the advantages, usage methods and precautions of simulated transactions in detail to help you stabilize the cryptocurrency market.

Gate.io Sesame Open Exchange App Download Guide: This article explains the official Gate.io Exchange App Download Method to help you trade cryptocurrency anytime, anywhere. Gate.io App has the advantages of convenience, good user experience, comprehensive functions (spot, contract, leverage, financial management, etc.) and strong security, and provides real-time market information. To ensure safety, be sure to download the App from the official website of Gate.io to avoid downloading malware. The article introduces the official website download steps and iOS and Android installation procedures in detail, and provides frequently asked questions and security suggestions to help you quickly get started with the Gate.io App and start a safe and convenient cryptocurrency trading journey.

This article introduces how to download the official Gate.io (Sesame Open Door) exchange app to help you trade cryptocurrency anytime, anywhere. The advantages of Gate.io App are convenience, smooth user experience, comprehensive trading functions (spot, contract, leverage, financial management, etc.), and powerful security, and provide real-time market information. The article explains in detail the steps to download the app through the official website, including the installation method of Android and iOS systems, and emphasizes the importance of downloading from official channels to avoid malware. In addition, the article also provides frequently asked questions and security suggestions to help users complete download and installation smoothly and ensure account security. Choose Gate.io to start your cryptocurrency investment journey!
