安装/配置
在线手册:中文  英文

运行时配置

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

会话配置选项
名字 默认 可修改范围 更新日志
session.save_path "" PHP_INI_ALL  
session.name "PHPSESSID" PHP_INI_ALL  
session.save_handler "files" PHP_INI_ALL  
session.auto_start "0" PHP_INI_ALL  
session.gc_probability "1" PHP_INI_ALL  
session.gc_divisor "100" PHP_INI_ALL 自 PHP 4.3.2 起可用。
session.gc_maxlifetime "1440" PHP_INI_ALL  
session.serialize_handler "php" PHP_INI_ALL  
session.cookie_lifetime "0" PHP_INI_ALL  
session.cookie_path "/" PHP_INI_ALL  
session.cookie_domain "" PHP_INI_ALL  
session.cookie_secure "" PHP_INI_ALL 自 PHP 4.0.4 起有效。
session.cookie_httponly "" PHP_INI_ALL 自 PHP 5.2.0. 有效
session.use_cookies "1" PHP_INI_ALL  
session.use_only_cookies "1" PHP_INI_ALL 自 PHP 4.3.0 起可用。
session.referer_check "" PHP_INI_ALL  
session.entropy_file "" PHP_INI_ALL  
session.entropy_length "0" PHP_INI_ALL  
session.cache_limiter "nocache" PHP_INI_ALL  
session.cache_expire "180" PHP_INI_ALL  
session.use_trans_sid "0" PHP_INI_ALL 在 PHP <= 4.2.3 是 PHP_INI_ALL,在 PHP < 5 是 PHP_INI_PERDIR。自 PHP 4.0.3 起可用。
session.bug_compat_42 "1" PHP_INI_ALL 自 PHP 4.3.0 起可用。
session.bug_compat_warn "1" PHP_INI_ALL 自 PHP 4.3.0 起可用。
session.hash_function "0" PHP_INI_ALL 自 PHP 5.0.0 起可用。
session.hash_bits_per_character "4" PHP_INI_ALL 自 PHP 5.0.0 起可用。
url_rewriter.tags "a=href,area=href,frame=src,form=,fieldset=" PHP_INI_ALL 自 PHP 4.0.4 起可用。
session.upload_progress.enabled "1" PHP_INI_PERDIR Available since PHP 5.4.0.
session.upload_progress.cleanup "1" PHP_INI_PERDIR Available since PHP 5.4.0.
session.upload_progress.prefix "upload_progress_" PHP_INI_PERDIR Available since PHP 5.4.0.
session.upload_progress.name "PHP_SESSION_UPLOAD_PROGRESS" PHP_INI_PERDIR Available since PHP 5.4.0.
session.upload_progress.freq "1%" PHP_INI_PERDIR Available since PHP 5.4.0.
session.upload_progress.min_freq "1" PHP_INI_PERDIR Available since PHP 5.4.0.
有关 PHP_INI_* 样式的更多详情与定义,见 配置可被设定范围

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

session.save_handler string
session.save_handler 定义了来存储和获取与会话关联的数据的处理器的名字。默认为 files。参见 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 可以用来做这件事。此外注意如果使用了 N 参数并且 N 大于 0,那么将不会执行自动垃圾回收,更多信息见 php.ini。另外如果用了 N 参数,要确保将 session.save_path 的值用双引号 "quotes" 括起来,因为分隔符分号( ;)在 php.ini 中也是注释符号。

Warning

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

Note: 在 PHP 4.3.6 之前,Windows 用户必须修改此选项以使用 PHP 的会话函数。必须指定一个合法路径,例如:c:/temp

session.name string
session.name 指定会话名以用做 cookie 的名字。只能由字母数字组成,默认为 PHPSESSID。参见 session_name()
session.auto_start boolean
session.auto_start 指定会话模块是否在请求开始时自动启动一个会话。默认为 0(不启动)。
session.serialize_handler string
session.serialize_handler 定义用来序列化/解序列化的处理器名字。当前支持 PHP 内部格式(名为 php)和 WDDX(名为 wddx)。如果 PHP 编译时加入了 WDDX 支持,则只能用 WDDX。默认为 php
session.gc_probability integer
session.gc_probabilitysession.gc_divisor 合起来用来管理 gc(garbage collection 垃圾回收)进程启动的概率。默认为 1。详见 session.gc_divisor
session.gc_divisor integer
session.gc_divisorsession.gc_probability 合起来定义了在每个会话初始化时启动 gc(garbage collection 垃圾回收)进程的概率。此概率用 gc_probability/gc_divisor 计算得来。例如 1/100 意味着在每个请求中有 1% 的概率启动 gc 进程。session.gc_divisor 默认为 100
session.gc_maxlifetime integer
session.gc_maxlifetime 指定过了多少秒之后数据就会被视为“垃圾”并被清除。

Note:

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

Note: 如果使用默认的基于文件的会话处理器,则文件系统必须保持跟踪访问时间(atime)。Windows FAT 文件系统不行,因此如果必须使用 FAT 文件系统或者其他不能跟踪 atime 的文件系统,那就不得不想别的办法来处理会话数据的垃圾回收。自 PHP 4.2.3 起用 mtime(修改时间)来代替了 atime。因此对于不能跟踪 atime 的文件系统也没问题了。

session.referer_check string
session.referer_check 包含有用来检查每个 HTTP Referer 的子串。如果客户端发送了 Referer 信息但是在其中并未找到该子串,则嵌入的会话 ID 会被标记为无效。默认为空字符串。
session.entropy_file string
session.entropy_file 给出了一个到外部资源(文件)的路径,该资源将在会话 ID 创建进程中被用作附加的熵值资源。例如在许多 Unix 系统下都可以用 /dev/random/dev/urandom
session.entropy_length integer
session.entropy_length 指定了从上面的文件中读取的字节数。默认为 0(禁用)。
session.use_cookies boolean
session.use_cookies 指定是否在客户端用 cookie 来存放会话 ID。默认为 1(启用)。
session.use_only_cookies boolean
session.use_only_cookies 指定是否在客户端仅仅使用 cookie 来存放会话 ID。。启用此设定可以防止有关通过 URL 传递会话 ID 的攻击。此设定是 PHP 4.3.0 添加的。
session.cookie_lifetime integer
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 boolean
session.cookie_secure 指定是否仅通过安全连接发送 cookie。默认为 off。此设定是 PHP 4.0.4 添加的。参见 session_get_cookie_params()session_set_cookie_params()
session.cookie_httponly boolean
Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).
session.cache_limiter string
session.cache_limiter 指定会话页面所使用的缓冲控制方法(none/nocache/private/private_no_expire/public)。默认为 nocache。参见 session_cache_limiter()
session.cache_expire integer
session.cache_expire 以分钟数指定缓冲的会话页面的存活期,此设定对 nocache 缓冲控制方法无效。默认为 180。参见 session_cache_expire()
session.use_trans_sid boolean
session.use_trans_sid 指定是否启用透明 SID 支持。默认为 0(禁用)。

Note: 对于 PHP 4.1.2 或以下版本,可以通过加入 --enable-trans-sid 配置选项去编译来启用,从 PHP 4.2.0 起,trans-sid 特性总是被编译。 基于 URL 的会话管理比基于 cookie 的会话管理有更多安全风险。例如用户有可能通过 email 将一个包含有效的会话 ID 的 URL 发给他的朋友,或者用户总是有可能在收藏夹中存有一个包含会话 ID 的 URL 来以同样的会话 ID 去访问站点。

session.bug_compat_42 boolean
PHP 4.2.3 以及更低版本有一个未公开的特性/错误,它允许用户在 register_globals 被禁用的情况下在全局范围内初始化一个会话变量。PHP 4.3.0 及更高版本会在使用此特性时并且启用了 session.bug_compat_warn 时发出警告。此特性/错误可以通过关闭此选项而禁用。
session.bug_compat_warn boolean
PHP 4.2.3 以及更低版本有一个未公开的特性/错误,它允许用户在 register_globals 被禁用的情况下在全局范围内初始化一个会话变量。PHP 4.3.0 及更高版本会在使用此特性时并且同时启用了 session.bug_compat_42session.bug_compat_warn 时发出警告。
session.hash_function integer
session.hash_function 允许用户指定生成会话 ID 的散列算法。'0' 表示 MD5(128 位),'1' 表示 SHA-1(160 位)。

Note:

这是 PHP 5 引进的。

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

Note:

这是 PHP 5 引进的。

url_rewriter.tags string
url_rewriter.tags 指定在使用透明 SID 支持时哪些 HTML 标记会被修改以加入会话 ID。默认为 a=href,area=href,frame=src,input=src,form=fakeentry,fieldset=

Note: 如果要符合 XHTML,去掉 form 项并在表单字段前后加上 <fieldset> 标记。

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.

Note: 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 integer
The minimum delay between updates, in seconds. Defaults to "1" (one second).

The track_vars and register_globals configuration settings influence how the session variables get stored and restored.

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.

track_varsregister_globals 配置选项影响到会话变量是怎样存储和恢复的。

Note:

自 PHP 4.0.3 起,track_vars 总是打开的。


安装/配置
在线手册:中文  英文

用户评论:

jlevene at etisoftware dot com (2013-02-21 01:29:33)

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

hassankhodadadeh at NOSPAM dot gmail dot com (2012-03-20 17:42:42)

max value for "session.gc_maxlifetime" is 65535. values bigger than this may cause php session stops working.

AskApache (2010-11-10 22:00:19)

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.

orbill (2010-08-30 05:08:54)

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.

Nicholas (2010-08-26 11:08:38)

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

Wouter (2010-05-19 03:14:35)

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)

VIPSoft (2009-07-27 14:23:51)

session.auto_start should always be "Off".
session.auto_start=On is considered "wrong" by Zend_Session as it causes an E_NOTICE to be thrown when Zend_Session::start() is called (either directly or indirectly, e.g., through Zend_Session_Namespace).

mikaelkael at php dot net (2009-01-28 12:50:45)

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'));

sony-santos at bol dot com dot br (2008-10-16 11:17:06)

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).

00 at f00n dot com (2008-06-25 06:36:22)

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

phpforcharity dot 5 dot pistos at geoshell dot com (2008-06-24 06:05:58)

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!

易百教程