An Permission denied Notice solution encountered by PHP using Session
- 2021-07-10 18:57:59
- OfStack
If you use PHP installed with apt under ubuntu/Debian, you may have a small probability of encountering this prompt when using 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
This is because, in PHP, if file_handler is used as save handler of Session, there is a probability that the Gc process of Session will be run every time session_start.
// Have ellipsis
int nrdels = -1;
nrand = (int) ((float) PS(gc_divisor) * php_combined_lcg(TSRMLS_C));
if (nrand < PS(gc_probability)) {
PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &nrdels TSRMLS_CC);
}
// Have ellipsis
The reason for this warning is that in PHP of apt, the default directory of session/var/lib/php5 has permissions of 733 with sticky bit, which is
drwx-wx-wt root root
While worker of PHP runs in a non-root identity, so there is no permission to open this folder (but because write can be used, it does not affect the normal reading of Session files). Therefore, the following code in s_gc will trigger the Notice mentioned at the beginning:
// For file handler To say , s_gc Indirect call ps_files_cleanup_dir:
dir = opendir(dirname);
if (!dir) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE,
"ps_files_cleanup_dir: opendir(%s) failed: %s (%d)",
dirname, strerror(errno), errno);
return (0);
}
Of course, under ubuntu/Debian, there is still gc recycling, which is only completed by the external cron process, and the default is/etc/cron. d/php5:,
09,39 * * * * root [ -x /usr/lib/php5/maxlifetime ]
&& [ -d /var/lib/php5 ] && find /var/lib/php5/
-type f -cmin +$(/usr/lib/php5/maxlifetime) -print0
| xargs -n 200 -r -0 rm
In addition, you can see that when judging whether s_gc is running, there are two key variables: PS (gc_divisor) and PS (gc_probability), which correspond to two configuration items with the same name of the runtime configuration item of session respectively:
session.gc_probability and session.gc_divisor, which default to 1 and 100, respectively.
php_combined_lcg is a random number generator that generates random numbers in the range of 0 to 1, so the above discrimination is equivalent to:
rand < probability / gc_divisor
That is, by default, the gc procedure can be called almost once every 100 times, so there is a small probability that this Notice can be seen.
To turn off this Notice, you only need to set:
session.gc_probability = 0, making it impossible for s_gc to run at all.
Of course, you can also change the permissions of this folder …