CakeFest 2024: The Official CakePHP Conference

运行时配置

这些函数的行为受 php.ini 中的设置影响。

会话配置选项
名字 默认 可修改范围 更新日志
session.save_path "" INI_ALL  
session.name "PHPSESSID" INI_ALL  
session.save_handler "files" INI_ALL  
session.auto_start "0" INI_PERDIR  
session.gc_probability "1" INI_ALL  
session.gc_divisor "100" INI_ALL  
session.gc_maxlifetime "1440" INI_ALL  
session.serialize_handler "php" INI_ALL  
session.cookie_lifetime "0" INI_ALL  
session.cookie_path "/" INI_ALL  
session.cookie_domain "" INI_ALL  
session.cookie_secure "0" INI_ALL 在 PHP 7.2.0 之前,默认值是 ""
session.cookie_httponly "0" INI_ALL 在 PHP 7.2.0 之前,默认值是 ""
session.cookie_samesite "" INI_ALL 自 PHP 7.3.0 起有效
session.use_strict_mode "0" INI_ALL 自 PHP 5.5.2 起有效
session.use_cookies "1" INI_ALL  
session.use_only_cookies "1" INI_ALL  
session.referer_check "" INI_ALL  
session.cache_limiter "nocache" INI_ALL  
session.cache_expire "180" INI_ALL  
session.use_trans_sid "0" INI_ALL  
session.trans_sid_tags "a=href,area=href,frame=src,form=" INI_ALL 自 PHP 7.1.0 起有效。
session.trans_sid_hosts $_SERVER['HTTP_HOST'] INI_ALL 自 PHP 7.1.0 起有效。
session.sid_length "32" INI_ALL 自 PHP 7.1.0 起有效。
session.sid_bits_per_character "4" INI_ALL 自 PHP 7.1.0 起有效。
session.upload_progress.enabled "1" INI_PERDIR  
session.upload_progress.cleanup "1" INI_PERDIR  
session.upload_progress.prefix "upload_progress_" INI_PERDIR  
session.upload_progress.name "PHP_SESSION_UPLOAD_PROGRESS" INI_PERDIR  
session.upload_progress.freq "1%" INI_PERDIR  
session.upload_progress.min_freq "1" INI_PERDIR  
session.lazy_write "1" INI_ALL  
session.hash_function "0" INI_ALL 自 PHP 7.1.0 起移除。
session.hash_bits_per_character "4" INI_ALL 自 PHP 7.1.0 起移除。
session.entropy_file "" INI_ALL 自 PHP 7.1.0 起移除。
session.entropy_length "0" INI_ALL 自 PHP 7.1.0 起移除。
有关 INI_* 样式的更多详情与定义,见 配置可被设定范围

会话管理系统支持许多配置选项,可以在自己的 php.ini 文件中设定。这里只是个简短的概览。

session.save_handler string
session.save_handler 定义处理器(handler)名称,可以获取/储存关联 session 数据。 默认为 files。 注意不同的扩展可能会注册它们各自的 save_handlerphpinfo() 提到的预装数据,包含了注册过的 hander。 可以参考 session_set_save_handler()
session.save_path string
session.save_path 定义了传递给存储处理器的参数。如果选择了默认的 files 文件处理器,则此值是创建文件的路径。默认为 /tmp。参见 session_save_path()

此指令还有一个可选的 N 参数来决定会话文件分布的目录深度。例如,设定为 '5;/tmp' 将使创建的会话文件和路径类似于 /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If。要使用 N 参数,必须在使用前先创建好这些目录。在 ext/session 目录下有个小的 shell 脚本名叫 mod_files.sh,windows 版本是 mod_files.bat 可以用来做这件事。此外注意如果使用了 N 参数并且大于 0,那么将不会执行自动垃圾回收,更多信息见 php.ini。另外如果用了 N 参数,要确保将 session.save_path 的值用双引号 "quotes" 括起来,因为分隔符分号( ;)在 php.ini 中也是注释符号。

文件储存模块默认使用 mode 600 创建文件。通过 修改可选参数 MODE 来改变这种默认行为: N;MODE;/path ,其中 MODE 是 mode 的八进制表示。 MODE 设置不影响进程的掩码(umask)。

警告

如果将此设定为一个全局可读的目录,例如 /tmp(默认值),服务器上的其他用户有可能通过该目录的文件列表破解会话。

警告

使用以上描述的可选目录层级参数 N 时请注意,对于绝大多数站点, 大于1或者2的值会不太合适——因为这需要创建大量的目录: 例如,值设置为 3 需要在文件系统上创建 64^3 个目录, 将浪费很多空间和 inode。

仅仅在绝对肯定站点足够大时,才可以设置 N 大于2。

session.name string
session.name 指定会话名以用做 cookie 的名字。只能由字母数字组成,默认为 PHPSESSID。参见 session_name()
session.auto_start bool
session.auto_start 指定会话模块是否在请求开始时自动启动一个会话。默认为 0(不启动)。
session.serialize_handler string
session.serialize_handler 定义用来序列化/反序列化的处理器名字。 当前支持 PHP 序列化格式 (名为 php_serialize)、 PHP PHP 内部格式 (名为 phpphp_binary) 和 WDDX (名为 wddx)。 如果 PHP 编译时加入了 WDDX 支持,则只能用 WDDX。 php_serialize 在内部简单地直接使用 serialize/unserialize 函数,并且不会有 phpphp_binary 所具有的限制。 使用较旧的序列化处理器导致 $_SESSION 的索引既不能是数字也不能包含特殊字符(| and !) 。 使用 php_serialize 避免脚本退出时,数字及特殊字符索引导致出错。 默认使用 php
session.gc_probability int
session.gc_probabilitysession.gc_divisor 合起来用来管理 gc(garbage collection 垃圾回收)进程启动的概率。默认为 1。详见 session.gc_divisor
session.gc_divisor int
session.gc_divisorsession.gc_probability 合起来定义了在每个会话初始化时启动 gc(garbage collection 垃圾回收)进程的概率。此概率用 gc_probability/gc_divisor 计算得来。例如 1/100 意味着在每个请求中有 1% 的概率启动 gc 进程。session.gc_divisor 默认为 100
session.gc_maxlifetime int
session.gc_maxlifetime 指定过了多少秒之后数据就会被视为“垃圾”并被清除。 垃圾搜集可能会在 session 启动的时候开始(取决于 session.gc_probabilitysession.gc_divisor)。 默认为 1440(24分钟)。

注意:

如果不同的脚本具有不同的 session.gc_maxlifetime 数值但是共享了同一个地方存储会话数据,则具有最小数值的脚本会清理数据。此情况下,与 session.save_path 一起使用本指令。

session.referer_check string
session.referer_check 包含有用来检查每个 HTTP Referer 的子串。如果客户端发送了 Referer 信息但是在其中并未找到该子串,则嵌入的会话 ID 会被标记为无效。默认为空字符串。
session.entropy_file string
session.entropy_file 给出了一个到外部资源(文件)的路径,该资源将在会话 ID 创建进程中被用作附加的熵值资源。例如在许多 Unix 系统下都可以用 /dev/random/dev/urandom 在 Windows 上也支持此功能。 设置 session.entropy_length 为非零的值将使 PHP 使用 Windows Random API 作为熵值源。

注意: PHP 7.1.0 中移除。 /dev/urandom/dev/arandom 可用的时候, session.entropy_file 默认使用它们。

session.entropy_length int
session.entropy_length 指定了从上面的文件中读取的字节数。默认为 0(禁用)。 PHP 7.1.0 中移除。
session.use_strict_mode bool
session.use_strict_mode 设置是否启用严格 session id 模式。 开启此模式后,模块不会接受未初始化过的 session ID。 从浏览器端传入未初始化的 session ID 后,将会发送一个新的 session ID 给它。 通过 session 启用严格模式可固定 session 以保护应用。 默认为 0 (禁用)。

注意: 开启 session.use_strict_mode 是常规的 session 安全强制性措施。 建议所有站点都开启此模式。 可以参考 session_create_id() 例子中的代码。

警告

如果 session_set_save_handler() 注册的自定义 session 处理器 没有实现 SessionUpdateTimestampHandlerInterface::validateId(), 也没有相应提供 validate_sid 回调,那么无论上述指令的值如何设置, 实际上严格 session ID 模式都是关闭状态的。 尤其需要注意没有 实现 SessionHandler::validateId()SessionHandler

session.use_cookies bool
session.use_cookies 指定是否在客户端用 cookie 来存放会话 ID。默认为 1(启用)。
session.use_only_cookies bool
session.use_only_cookies 指定是否在客户端仅仅使用 cookie 来存放会话 ID。启用此设定可以防止有关通过 URL 传递会话 ID 的攻击。默认值为1(启用)。
session.cookie_lifetime int
session.cookie_lifetime 以秒数指定了发送到浏览器的 cookie 的生命周期。值为 0 表示“直到关闭浏览器”。默认为 0。参见 session_get_cookie_params()session_set_cookie_params()

注意:

过期时间是根据服务器时间设置的, 它没有必要和浏览器端的时间一致。

session.cookie_path string
session.cookie_path 指定了要设定会话 cookie 的路径。默认为 /。参见 session_get_cookie_params()session_set_cookie_params()
session.cookie_domain string
session.cookie_domain 指定了要设定会话 cookie 的域名。默认为无,表示根据 cookie 规范产生 cookie 的主机名。参见 session_get_cookie_params()session_set_cookie_params()
session.cookie_secure bool
session.cookie_secure 指定是否仅通过安全连接发送 cookie。默认为 off。此设定是 PHP 4.0.4 添加的。参见 session_get_cookie_params()session_set_cookie_params()
session.cookie_httponly bool
设置 cookie 仅能够通过 HTTP 协议访问。 它意味着 cookie 无法通过类似 JavaScript 这样的脚本语言访问。 该设置可有效避免 XSS 攻击窃取身份(但并非所有浏览器都支持)。
session.cookie_samesite string
Allows servers to assert that a cookie ought not to be sent along with cross-site requests. This assertion allows user agents to mitigate the risk of cross-origin information leakage, and provides some protection against cross-site request forgery attacks. Note that this is not supported by all browsers. An empty value means that no SameSite cookie attribute will be set. Lax and Strict mean that the cookie will not be sent cross-domain for POST requests; Lax will send the cookie for cross-domain GET requests, while Strict will not.
session.cache_limiter string
session.cache_limiter 指定会话页面所使用的缓冲控制方法( none/nocache/ private/ private_no_expire/public)。默认为 nocache。参见 session_cache_limiter() 文档查看各个值的含义。
session.cache_expire int
session.cache_expire 以分钟数指定缓冲的会话页面的存活期,此设定对 nocache 缓冲控制方法无效。默认为 180。参见 session_cache_expire()
session.use_trans_sid bool
session.use_trans_sid 指定是否启用透明 SID 支持。默认为 0(禁用)。

注意: 基于 URL 的会话管理比基于 cookie 的会话管理有更多安全风险。例如用户有可能通过 email 将一个包含有效的会话 ID 的 URL 发给他的朋友,或者用户总是有可能在收藏夹中存有一个包含会话 ID 的 URL 来以同样的会话 ID 去访问站点。 自 PHP 7.1.0 开始,透明 SID 开始使用完整的 URL 绝对路径,例如 https://php.net/。 在此之前 PHP 只会使用相对路径。使用 session.trans_sid_hosts 定义重写的目标 host。

session.trans_sid_tags string
开启支持透明 sid 时, session.trans_sid_tags 指定是否需要重写 HTML 标签来包含 session id。 默认为 a=href,area=href,frame=src,input=src,form= form 是个特殊标签。 <input hidden="session_id" name="session_name"> 作为表单变量添加。

注意: PHP 7.1.0 之前,url_rewriter.tags 用于此目的。 PHP 7.1.0 之后,fieldset 不再作为特殊标签对待。

session.trans_sid_hosts string
当透明 sid 支持开启时,session.trans_sid_hosts 设置了要重写包含 session 的主机名, 默认为 $_SERVER['HTTP_HOST']。 多个主机用半角逗号 "," 分隔;主机名之间不能用空格。 例如 php.net,wiki.php.net,bugs.php.net
session.sid_length int
通过 session.sid_length 可以设置 session ID 字符串长度。 Session ID 的长度可以是在 22 到 256 之间。 默认是 32。 如果需要较好的兼容性可以设置为 32、40 等。 较长的 session ID 会更难猜测。 推荐至少要 32 个字符。
小技巧

Compatibility Note: Use 32 instead of session.hash_function=0 (MD5) and session.hash_bits_per_character=4, session.hash_function=1 (SHA1) and session.hash_bits_per_character=6. Use 26 instead of session.hash_function=0 (MD5) and session.hash_bits_per_character=5. Use 22 instead of session.hash_function=0 (MD5) and session.hash_bits_per_character=6. 必须正确配置 INI 值,让 session ID 至少有 128 比特(bits)。 不要忘了为 session.sid_bits_per_character 设置合适的值;否则将会有一个较弱的 session ID。

注意: PHP 7.1.0 中加入该设置。

session.sid_bits_per_character int
session.sid_bits_per_character 设置要编码 session ID 字符的比特数。 可能的设置有: '4'(0-9、a-f)、'5'(0-9、a-v)、'6'(0-9、a-z、A-Z、"-"、",")。 默认为 4。 更多的比特数会产生更强健的 session ID。 对于绝大多数环境,推荐值是 5。

注意: PHP 7.1.0 中加入该设置。

session.hash_function mixed
session.hash_function 允许用户指定生成会话 ID 的散列算法。'0' 表示 MD5(128 位),'1' 表示 SHA-1(160 位)。

还可以指定 hash 扩展(开启的时候) 支持的任意算法,例如 sha512whirlpool。 可通过 hash_algos() 函数获取支持的算法完整名单。

注意:

PHP 7.1.0 中已经移除。

session.hash_bits_per_character int
session.hash_bits_per_character 允许用户定义将二进制散列数据转换为可读的格式时每个字符存放多少个比特。可能值为 '4'(0-9,a-f),'5'(0-9,a-v),以及 '6'(0-9,a-z,A-Z,"-",",")。

注意:

这是 PHP 5 引进的。

session.upload_progress.enabled boolean
Enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled.
session.upload_progress.cleanup boolean
Cleanup the progress information as soon as all POST data has been read (i.e. upload completed). Defaults to 1, enabled.

注意: It is highly recommended to keep this feature enabled.

session.upload_progress.prefix string
A prefix used for the upload progress key in the $_SESSION. This key will be concatenated with the value of $_POST[ini_get("session.upload_progress.name")] to provide a unique index. Defaults to "upload_progress_".
session.upload_progress.name string
The name of the key to be used in $_SESSION storing the progress information. See also session.upload_progress.prefix. If $_POST[ini_get("session.upload_progress.name")] is not passed or available, upload progressing will not be recorded. Defaults to "PHP_SESSION_UPLOAD_PROGRESS".
session.upload_progress.freq mixed
Defines how often the upload progress information should be updated. This can be defined in bytes (i.e. "update progress information after every 100 bytes"), or in percentages (i.e. "update progress information after receiving every 1% of the whole filesize"). Defaults to "1%".
session.upload_progress.min_freq int
The minimum delay between updates, in seconds. Defaults to "1" (one second).
session.lazy_write bool
session.lazy_write,设置成 1 的含义是: 只有 session 数据发生变化时才需要重新写入。默认为开启状态 1。

Upload progress will not be registered unless session.upload_progress.enabled is enabled, and the $_POST[ini_get("session.upload_progress.name")] variable is set. See Session Upload Progress for mor details on this functionality.

add a note

User Contributed Notes 25 notes

up
34
Walerian Walawski - https://w87.eu/
5 months ago
Can't find mod_files.sh? Here it is:
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

#!/usr/bin/env bash

if [[ "$2" = "" ]] || [[ "$3" = "" ]]; then
echo "Usage: $0 BASE_DIRECTORY DEPTH BITS_PER_CHAR"
echo "BASE_DIRECTORY will be created if it doesn't exist"
echo "DEPTH must be an integer number >0"
echo "BITS_PER_CHAR(session.sid_bits_per_character) should be one of 4, 5, or 6."
# http://php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character
exit 1
fi

if [[ "$2" = "0" ]] && [[ ! "$4" = "recurse" ]]; then
echo "Can't create a directory tree with depth of 0, exiting."
fi

if [[ "$2" = "0" ]]; then
exit 0
fi

directory="$1"
depth="$2"
bitsperchar="$3"

hash_chars="0 1 2 3 4 5 6 7 8 9 a b c d e f"

if [[ "$bitsperchar" -ge "5" ]]; then
hash_chars="$hash_chars g h i j k l m n o p q r s t u v"
fi

if [[ "$bitsperchar" -ge "6" ]]; then
hash_chars="$hash_chars w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - ,"
fi

while [[ -d $directory ]] && [[ $( ls $directory ) ]]; do
echo "Directory $directory is not empty! What would you like to do?"

options="\"Delete directory contents\" \"Choose another directory\" \"Quit\""
eval set $options
select opt in "$@"; do

if [[ $opt = "Delete directory contents" ]]; then
echo "Deleting $directory contents... "
rm -rf $directory/*
elif [[ $opt = "Choose another directory" ]]; then
echo "Which directory would you like to choose?"
read directory
elif [[ $opt = "Quit" ]]; then
exit 0
fi

break;
done
done

if [[ ! -d $directory ]]; then
mkdir -p $directory
fi

echo "Creating session path in $directory with a depth of $depth for session.sid_bits_per_character = $bitsperchar"

for i in $hash_chars; do
newpath="$directory/$i"
mkdir $newpath || exit 1
bash $0 $newpath `expr $depth - 1` $bitsperchar recurse
done
up
77
Christopher Kramer
9 years ago
On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime).

You can adjust the global value in your php.ini (usually /etc/php5/apache2/php.ini). Or you can change the session.save_path so debian's cronjob will not clean up your sessions anymore. Then you need to either do your own garbage collection with your own cronjob or enable PHP's garbage collection (php then needs sufficient privileges on the save_path).

Why does Debian not use PHP's garbarage collection?
For security reasons, they store session data in a place (/var/lib/php5) with very stringent permissions. With the sticky bit set, only root is allowed to rename or delete files there, so PHP itself cannot clean up old session data. See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=267720 .
up
18
GreenReaper
9 years ago
We found a session.save_path depth of 3 led to excessive wastage of inodes and in fact disk space in storing the directory tree. dir_indexes option on ext2/3/4 makes larger directories more feasible anyway, so we decided to move to a depth of 2 instead.

It took a little puzzling to figure out how to move the existing PHP sessions up one directory tree, but we ended up running this in the root sessions directory:

#!/bin/sh
for a in ./* ; do
cd ./$a
pwd
for b in ./* ; do
cd ./$b
pwd
# Move existing sessions out
find ./* -xdev -type f -print0 | xargs -0 mv -t .
# Remove subdirectories
find ./* -xdev -type d -print0 | xargs -0 rmdir
cd ..
done
cd ..
done

This script may not be the best way to do it, but it got the job done fast. You can modify it for different depths by adding or removing "for" loops.

The documentation gives a depth of 5 as an example, but five is right out. If you're going beyond 2, you're at the scale where you may want to to look at a large memcached or redis instance instead.
up
16
info at thimbleopensource dot com
8 years ago
I found out that if you need to set custom session settings, you only need to do it once when session starts. Then session maintains its settings, even if you use ini_set and change them, original session still will use it's original setting until it expires.

Just thought it might be useful to someone.
up
1
zch1
3 months ago
the pwd should be urlencode when it contanis special chars.
eg:

save_handler:redis
save_path: tcp://127.0.0.1:6739?auth=urlencode('xxxxx')
up
5
boan dot web at outlook dot com
5 years ago
session.cache_limiter may be empty string to disable cache headers entirely.

Quote:
> Setting the cache limiter to '' will turn off automatic sending of cache headers entirely.

http://php.net/manual/en/function.session-cache-limiter.php
up
8
Wouter
13 years ago
When setting the session.cookie_lifetime directive in a .htaccess use string format like;

php_value session.cookie_lifetime "123456"

and not

php_value session.cookie_lifetime 123456

Using a integer as stated above dit not work in my case (Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.5 with Suhosin-Patch mod_ssl/2.2.11 OpenSSL/0.9.8g)
up
7
jlevene at etisoftware dot com
11 years ago
Being unable to find an actual copy of mod_files.sh, and seeing lots of complaints/bug fix requests for it, here's one that works. It gets all its parameters from PHP.INI, so you don't have the opportunity to mess up:

#!/bin/bash
#
# Creates directories for PHP session storage.
# Replaces the one that "comes with" PHP, which (a) doesn't always come with it
# and (b) doesn't work so great.
#
# This version takes no parameters, and uses the values in PHP.INI (if it
# can find it).
#
# Works in OS-X and CentOS (and probably all other) Linux.
#
# Feb '13 by Jeff Levene.

[[ $# -gt 0 ]] && echo "$0 requires NO command-line parameters.
It gets does whatever is called for in the PHP.INI file (if it can find it).
" && exit 1

# Find the PHP.INI file, if possible:
phpIni=/usr/local/lib/php.ini # Default PHP.INI location
[[ ! -f "$phpIni" ]] && phpIni=/etc/php.ini # Secondary location
[[ ! -f "$phpIni" ]] && phpIni= # Found it?

# Outputs the given (as $1) parameter from the PHP.INI file:
# The "empty" brackets have a SPACE and a TAB in them.
#
PhpConfigParam() {
[[ ! "$phpIni" ]] && return
# Get the line from the INI file:
varLine=`grep "^[ ]*$1[ ]*=" "$phpIni"`

# Extract the value:
value=`expr "$varLine" : ".*$1[ ]*=[ ]*['\"]*\([^'\"]*\)"`
echo "$value"
}

if [[ "$phpIni" ]]
then
savePath=`PhpConfigParam session.save_path`
# If there's a number and semicolon at the front, remove them:
dirDepth=`expr "$savePath" : '\([0-9]*\)'`
[[ "$dirDepth" ]] && savePath=`expr "$savePath" : '[0-9]*;\(.*\)'` || dirDepth=0
bits=`PhpConfigParam session.hash_bits_per_character`
case "x$bits" in
x) echo "hash_bits_per_character not defined. Not running." ; exit 2 ;;
x4) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f' ;;
x5) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v' ;;
x6) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v'
alphabet="$alphabet w x y z A B C D E F G H I J K L M N O P Q R S T U V W"
alphabet="$alphabet X Y Z - ,"
;;
*) echo "unrecognized hash_bits_per_character. Not running." ; exit 2 ;;
esac
else
echo "Cannot find the PHP.INI file. Not running. Sorry."
exit 2
fi

# The depth of directories to create is $1. 0 means just create the named
# directory. Directory to start with is $2.
#
# Used recursively, so variables must be "local".

doDir() {
local dir="$2"
if [[ -d "$dir" ]]
then
echo "Directory '$dir' already exists. No problem."
elif [[ -f "$dir" ]]
then
echo "FILE '$dir' exists. Aborting." ; exit 2
else
if mkdir "$dir"
then
echo "Directory '$dir' created."
else
echo "Cannot create directory '$dir'. Aborting." ; exit 2
fi
fi
chmod a+rwx "$dir"
if [[ $1 -gt 0 ]]
then
local depth=$(( $1 - 1 ))
for letter in $alphabet
do doDir $depth "$dir/$letter"
done
fi
}


echo "Running with savePath='$savePath', dirDepth=$dirDepth, and bitsPerCharacter=$bits."
sleep 3

doDir $dirDepth "$savePath"

exit 0
up
7
hassankhodadadeh at NOSPAM dot gmail dot com
12 years ago
max value for "session.gc_maxlifetime" is 65535. values bigger than this may cause php session stops working.
up
2
li-lingjie
6 years ago
Use SessionHandlerInterface interface Custom redis session, found the following:

Use ini_set ('session.save_path', "tcp: //127.0.0.1: 6379? Auth = password"); will be reported:

PHP Fatal error: session_start (): Failed to initialize storage module: user (path: tcp: //127.0.0.1: 6379? Auth = password);

Using session_save_path ("tcp: //127.0.0.1: 6379? Auth = password") will not
up
3
Nicholas
13 years ago
Transient sessions do not appear to be working in 5.3.3

E.g.

<?php
ini_set
("session.use_cookies", 0);
ini_set("session.use_trans_sid", 1);
session_start();

if (isset(
$_SESSION["foo"])) {
echo
"Foo: " . $_SESSION["foo"];
} else {
$_SESSION["foo"] = "Bar";
echo
"<a href=?" . session_name() . "=" . session_id() . ">Begin test</a>";
}
?>

This works in 5.2.5, but not 5.3.3
up
1
theking2(at)king.ma
1 month ago
Please be careful with the 'sid_length' when setting 'sid_bits_per_character' to six.

Setting sid_bits_per_character to 6 includes the character "," to the list of possible characters. A comma will be escaped and transmitted as "%2C" (tested on Chromium Version 119.0.6045.199) adding two extra characters for each comma to the SESSION_ID.
up
0
theking2(at)king.ma
25 days ago
To prevent mitm-attacks you want to make sure the session cookie is only transmitted over a secure channel prefix it with the magic string "__Secure-". [1]

Like :
<?php
session_start
( [ 'name' => '__Secure-Session-ID' ] );
?>

The cookie will not be available on non-secure channel.

(Putting this note it here probably goes unnoticed because of all the noise)

[1]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
up
-1
usrhlp at yahoo dot com
23 days ago
The session.save-path doesn't work in 8.3.3 as it did in previous versions on windows / IIS.

upgrading from 8.1 to 8.3 causes the session save path to be interpreted differently.

To fix this you have to write the absolute path to the session folder location within php.ini.

An example on windows using IIS would be something along the lines of

C:\inetpub\wwwroot\sessiontmp

Leaving the session path line commented out or even specifying "\tmp" within php.ini causes the session path to be incorrectly assigned which prevents all sessions from being created. After manually adding the full local server path for your session temporary folder within PHP.INI, can sessions be created again.

Even creating the folders in the correct location within your inetpub folder fails to fix the issue with the 8.3.3.

Reverting back to PHP 8.1.26 also reverts the behaviour back to previous and all default PHP.INI settings work correctly and sessions can be created as expected. This shows it is an issue with PHP 8.3.3.

I spent 3 hours diagnosing that error hopefully i have saved you time too.
up
0
ohcc at 163 dot com
6 years ago
You should take more care configuring session.gc_maxlifetime when virtual hosts share the same session-saving directory. One host's session data may be gc'ed when another host runs php.
up
-1
AskApache
13 years ago
This is how I set my session.save_path
session.save_path = "1;/home/askapache/tmp/s"
So to create the folder structure you can use this compatible shell script, if you want to create with 777 permissions change the umask to 0000;
sh -o braceexpand -c "umask 0077;mkdir -p s/{0..9}/{a..z} s/{a..z}/{0..9}"

Then you can create a cronjob to clean the session folder by adding this to your crontab which deletes any session files older than an hour:
@daily find /home/askapache/tmp/s -type f -mmin +60 -exec rm -f {} \; &>/dev/null

That will create sessions in folder like:
/home/askapache/tmp/s/b/sess_b1aba5q6io4lv01bpc6t52h0ift227j6

I don't think any non-mega site will need to go more than 1 levels deep. Otherwise you create so many directories that it slows the performance gained by this.
up
-2
00 at f00n dot com
15 years ago
After having many problems with garbage collection not clearing my sessions I have resolved it through the following.

First I found this in the php.ini (not something i noticed as i use phpinfo(); to see my hosting ini).

; NOTE: If you are using the subdirectory option for storing session files
; (see session.save_path above), then garbage collection does *not*
; happen automatically. You will need to do your own garbage

; collection through a shell script, cron entry, or some other method. ; For example, the following script would is the equivalent of
; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
; cd /path/to/sessions; find -cmin +24 | xargs rm

With this is mind there are options.

1. dont use a custom save_path.
** This means if your isp hasnt defaulted your session temp to something safer than install default or you are using a shared directory for session data then you would be wise to use named sessions to keep your session from being viewable in other people's scripts. Creating a unique_id name for this is the common method. **

2. use your custom folder but write a garbage collection script.

3. use a custom handler and a database
up
-2
mikaelkael at php dot net
15 years ago
Recently, I needed to change the session save_path in my program under Windows. With an ini_set('session.save_path', '../data/sessions'); (and session.gc_divisor = 1 for test), I always obtain 'Error #8 session_start(): ps_files_cleanup_dir: opendir(../data/sessions) failed: Result too large'.

I corrected this by changing with ini_set('session.save_path', realpath('../data/sessions'));
up
-3
orbill
13 years ago
apparently the default value for session.use_only_cookies has changed in 5.3.3 from 0 to 1. If you haven't set this in your php.ini or your code to 0 transparent sessions won't work.
up
-4
white-gandalf at web dot de
6 years ago
session.use_strict_mode does very little to strengthen your security: only one very specific variant of attack is migitated by this (where the attacker hands an "empty" sid to the victim to adapt his own browser to that session later) - versus for example the case where he pre-opens a session, handing the sid of that one to the victim, so the victim gets adapted to the pre-opened session. In the latter case this flag does nothing to help. In every other scenario with other vulnerabilities where the session id gets leaked, the flag helps nigher.

But this flag renders the php function session_id() useless in its parameterized variant, thus preventing any php functionality that builds upon this function.
up
-2
polygon dot co dot in at gmail dot com
2 years ago
In php.ini, session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. [Defaults to files.]

By default session.save_handler has support for below

session.save_handler = files
session.save_handler = sqlite
session.save_handler = redis
session.save_handler = memcached

These locks the session by default for any HTTP request using session.
Locking means, a user can't access session related pages until current request is completed.

So, if you are thinking that switching to these will increase performance; the answer is NO! because of locking behaviour.

To overcome/customise the session locking behaviour use as below.

session.save_handler = user
This is for all (including list above) modes of session storage.

For "user" type save_handler, we can ignore locks for better performance (as explained in function session_set_save_handler). But for this we need to take care to use sessions only for authenticity and not for passing data from one script to other.

For passing data accross scripts use GET method to achieve the goal.
up
-1
descartavel1+php at gmail dot com
10 months ago
You should set `session.name` to use either prefix `__Host-` or `__Secure-`. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
up
-6
sony-santos at bol dot com dot br
15 years ago
In response to 00 at f00n, this very page explains:

"(...) if N is used and greater than 0 then automatic garbage collection will not be performed (...)"

So you can actually use custom save_path with automatic garbage collection, since you don't use the subdirectory option (that N subdirectory levels).
up
-16
phpforcharity dot 5 dot pistos at geoshell dot com
15 years ago
To get session IDs to show up in URIs, and not get stored via cookies, you must not only set session.use_cookies to 0, but also set session.use_trans_sid to 1. Otherwise, the session ID goes neither in a cookie nor in URIs!
up
-21
Anonymous
7 years ago
In response to this comment: http://php.net/manual/en/session.configuration.php#107990 where it is claimed that gc_maxlifetime values larger than 65535 break the session system. I cannot reproduce this.

I've set gc_maxlifetime to 31536000 (1 year) and the session system works just fine. I haven't tried how long a session lasts now (I'm in the process of testing this), but it certainly doesn't break PHP sessions.
To Top