search
HomeBackend DevelopmentPHP TutorialExample of strict control of session timeout in php_PHP tutorial

The default session timeout in PHP is 30 minutes, but sometimes it automatically times out before 30 minutes. This brings inconvenience to many operations. Let’s take a look at how to solve the 30-minute timeout.

First answer

Then, the most common answer is: Set the session expiration time, which is session.gc_maxlifetime. This answer is incorrect for the following reasons:

1. First of all, this PHP uses a certain probability to run the gc of the session, that is, session.gc_probability and session.gc_divisor (for introduction, please refer to the small probability Notice of Session Gc in In-depth Understanding of PHP Principles), this default The values ​​are 1 and 100 respectively, which means there is a 1% chance that PHP will run Session gc when a Session is started. There is no guarantee that it will expire in 30 minutes.

2. What about setting a high-probability cleanup opportunity? Still inappropriate, why? Because PHP uses the modification time of the stat Session file to determine whether it has expired. If this probability is increased, firstly, it will reduce performance. Secondly, PHP Use "a" file to save Session variables related to a session. Suppose I set a Session variable with a=1 5 minutes ago, and set a Seesion variable with b=2 5 minutes later. Then the modification of this Session file The time is the time when moment b is added, then a cannot be cleared at 30 minutes. There is also the third reason below.

3. By default, PHP (Linux as an example) uses /tmp as the default storage directory of Session, and the manual also has the following description:

Note: If different scripts have different session.gc_maxlifetime values ​​but share the same place to store session data, the script with the smallest value will clean up the data. In this case, use this directive together with session.save_path.

That is to say, if there are two applications that do not specify their own independent save_path, one sets the expiration time to 2 minutes (assumed to be A), and the other sets the expiration time to 30 minutes (assumed to be B), then each time A When the Session gc is running, the Session files belonging to application B will be deleted at the same time.

So, the first answer is not "completely strictly" correct.

The second answer
Another common answer is: Set the carrier of the Session ID and the expiration time of the Cookie, which is session.cookie_lifetime. This answer is also incorrect for the following reasons:

This expiration is just Cookie expiration. In other words, let’s examine the difference between Cookie and Session. Session expiration is server expiration, while Cookie expiration is guaranteed by the client (browser). Even if you set Cookie expiration, this only It can ensure that the standard browser will not send this cookie (containing Session ID) when it expires, and if you construct a request, you can still use the value of this Session ID.

The third answer
Using memcache, redis, okey, etc., this answer is a correct answer. However, obviously the questioner will definitely ask you next, what if you just use PHP?

The fourth answer
Of course, the interview is not for you, but to test the thoroughness of your thinking. During the process, I will point out these pitfalls, so generally speaking, the approach that meets the meaning of the question is:

1. Set the cookie expiration time to 30 minutes, and set the Session lifetime to 30 minutes.

2. Add Time stamp to each Session value yourself.

3. Before each visit, determine the timestamp.

Foreign website reference session.gc_maxlifetime

session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor).
Note:

If different scripts have different values ​​of session.gc_maxlifetime but share the same place for storing the session data then the script with the minimum value will be cleaning the data. In this case, use this directive together with session.save_path.


Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.

session.referer_check string
session.referer_check contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string.
session.entropy_file string
session.entropy_file gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process. Examples are /dev/random or /dev/urandom which are available on many Unix systems. This feature is supported on Windows since PHP 5.3.3. Setting session.entropy_length to a non zero value will make PHP use the Windows Random API as entropy source.
session.entropy_length integer
session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 0 (disabled).
session.use_cookies boolean


PHP原理之Session Gc的一个小概率Notice

如果在ubuntu/Debian下, 采用apt安装的PHP, 那么在使用Session的时候, 就可能会有小概率遇到这个提示.

PHP Notice: session_start(): ps_files_cleanup_dir:

   opendir(/var/lib/php5) failed: Permission denied (13)

   in /home/laruence/www/htdocs/index.php on line 22

 

这是因为, 在PHP中, 如果使用file_handler作为Session的save handler, 那么就有概率在每次session_start的时候运行Session的Gc过程.

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/632202.htmlTechArticlephp中session默认是30分钟超时,但是有的时间压根就没到30分钟就自动超时了,这对很多操作带来不便,下面我们来看看解决30分钟超时的办法...
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment