PHP 8.6.0 Alpha 2 available for testing

session_create_id

(PHP 7 >= 7.1.0, PHP 8)

session_create_id创建新的会话 ID

说明

function session_create_id(string $prefix = ""): string|false

session_create_id() 用于为当前会话创建新的会话 ID。它返回无冲突的会话 ID。

如果会话未处于活动状态,则会省略冲突检查。

会话 ID 根据 php.ini 的设置来创建。

重要的是,GC 任务脚本需要使用与 Web 服务器相同的用户 ID。 否则,可能会遇到权限问题,尤其是在使用文件保存处理程序时。

参数

prefix

如果指定了 prefix,新的会话 ID 将以 prefix 作为前缀。会话 ID 中并非所有字符都被允许。允许的字符范围为 [a-zA-Z0-9,-]。最大长度为 256 个字符。

返回值

session_create_id() 返回当前会话的新的无冲突会话 ID。如果在没有活动会话的情况下使用,则会省略冲突检查。 失败时返回 false

示例

示例 #1 session_create_id()session_regenerate_id() 的使用示例

<?php
// 自定义会话启动函数,支持时间戳管理
function my_session_start() {
    session_start();
    // 不允许使用过期的会话 ID
    if (!empty($_SESSION['deleted_time']) && $_SESSION['deleted_time'] < time() - 180) {
        session_destroy();
        session_start();
    }
}

// 自定义会话 ID 重新生成函数
function my_session_regenerate_id() {
    // 在会话活动时调用 session_create_id()
    // 以确保不会产生冲突。
    if (session_status() != PHP_SESSION_ACTIVE) {
        session_start();
    }
    // 警告:切勿使用机密字符串作为前缀!
    $newid = session_create_id('myprefix-');
    // 设置删除时间戳。会话数据不能立即删除,原因如下。
    $_SESSION['deleted_time'] = time();
    // 结束会话
    session_commit();
    // 确保接受用户定义的会话 ID
    // 注意:正常操作必须启用 use_strict_mode。
    ini_set('session.use_strict_mode', 0);
    // 设置新的自定义会话 ID
    session_id($newid);
    // 使用自定义会话 ID 启动
    session_start();
}

// 确保启用了 use_strict_mode。
// 出于安全原因,use_strict_mode 是必需的。
ini_set('session.use_strict_mode', 1);
my_session_start();

// 在以下情况下必须重新生成会话 ID:
//  - 用户登录时
//  - 用户登出时
//  - 经过一段时间后
my_session_regenerate_id();

// 编写有用的代码
?>

参见

添加备注

用户贡献的备注 1 note

up
4
rowan dot collins at gmail dot com
8 years ago
This function is very hard to replicate precisely in userland code, because if a session is already started, it will attempt to detect collisions using the new "validate_sid" session handler callback, which did not exist in earlier PHP versions.

If the handler you are using implements the "create_sid" callback, collisions may be detected there. This is called when you use session_regenerate_id(), so you could use that to create a new session, note its ID, then switch back to the old session ID. If no session is started, or the current handler doesn't implement "create_sid" and "validate_sid", neither this function nor session_regenerate_id() will guarantee collision resistance anyway.

If you have a suitable definition of random_bytes (a library is available to provide this for versions right back to PHP 5.3), you can use the following to generate a session ID in the same format PHP 7.1 would use. $bits_per_character should be 4, 5, or 6, corresponding to the values of the session.hash_bits_per_character / session.sid_bits_per_character ini setting. You will then need to detect collisions manually, e.g. by opening the session and confirming that $_SESSION is empty.

<?php
function session_create_random_id($desired_output_length, $bits_per_character)
{
    $bytes_needed = ceil($desired_output_length * $bits_per_character / 8);
    $random_input_bytes = random_bytes($bytes_needed);
    
    // The below is translated from function bin_to_readable in the PHP source (ext/session/session.c)
    static $hexconvtab = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-';
    
    $out = '';
    
    $p = 0;
    $q = strlen($random_input_bytes);
    $w = 0;
    $have = 0;
    
    $mask = (1 << $bits_per_character) - 1;

    $chars_remaining = $desired_output_length;
    while ($chars_remaining--) {
        if ($have < $bits_per_character) {
            if ($p < $q) {
                $byte = ord( $random_input_bytes[$p++] );
                $w |= ($byte << $have);
                $have += 8;
            } else {
                // Should never happen. Input must be large enough.
                break;
            }
        }

        // consume $bits_per_character bits
        $out .= $hexconvtab[$w & $mask];
        $w >>= $bits_per_character;
        $have -= $bits_per_character;
    }

    return $out;
}
?>
To Top