CakeFest 2024: The Official CakePHP Conference

session_create_id

(PHP 7 >= 7.1.0, PHP 8)

session_create_idCria novo ID de sessão

Descrição

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

session_create_id() é usado para criar um novo id de sessão para a sessão atual. Ele retorna um ID de sessão livre de colisão.

Se a sessão não estiver ativa, a verificação de colisão será omitida.

O id de sessão é criado de acordo com a configuração no php.ini.

É importante usar o mesmo ID de usuário do seu servidor web para o script de tarefa do GC. Caso contrário, você poderá ter problemas de permissão, especialmente com o gerenciador de salvamento de arquivos.

Parâmetros

prefix

Se prefix for especificado, o novo id de sessão é prefixado por prefix. Nem todos os caracteres são permitidos no ID da sessão. Caracteres entre a-z A-Z 0-9 , (vírgula) e - (sinal de menos) são permitidos.

Valor Retornado

session_create_id() retorna um novo id de sessão livre de colisão para a sessão atual. Se for usado sem uma sessão ativa, a verificação de colisão é omitida. Em caso de falha, false é retornado.

Exemplos

Exemplo #1 session_create_id() exemplo com session_regenerate_id()

<?php
// Minha função de início de sessão suporta gerenciamento de timestamp
function my_session_start() {
session_start();
// Não permitir o uso de ID de sessão muito antigo
if (!empty($_SESSION['deleted_time']) && $_SESSION['deleted_time'] < time() - 180) {
session_destroy();
session_start();
}
}

// Minha função de regeneração de id de sessão
function my_session_regenerate_id() {
// Chame session_create_id() enquanto a sessão estiver ativa
// para garantir que não haja colisões.
if (session_status() != PHP_SESSION_ACTIVE) {
session_start();
}
// AVISO: Nunca use strings confidenciais para prefixo!
$newid = session_create_id('myprefix-');
// Definir timestamp de exclusão. Os dados da sessão não devem ser excluídos imediatamente por motivos.
$_SESSION['deleted_time'] = time();
// Terminar sessão
session_commit();
// Certifique-se de aceitar o ID de sessão definido pelo usuário
// NOTA: Você deve ativar use_strict_mode para operações normais.
ini_set('session.use_strict_mode', 0);
// Define novo ID de sessão personalizado
session_id($newid);
// Comece com um ID de sessão personalizado
session_start();
}

// Certifique-se de que use_strict_mode está habilitado.
// use_strict_mode é obrigatório por motivos de segurança.
ini_set('session.use_strict_mode', 1);
my_session_start();

// O ID da sessão deve ser regenerado quando
// - Usuário se loga
// - Usuário se desloga
// - Certo período já passou
my_session_regenerate_id();

// Escreva códigos úteis
?>

Veja Também

add a note

User Contributed Notes 2 notes

up
4
rowan dot collins at gmail dot com
6 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;
}
?>
up
-4
haidz
5 years ago
I needed to use session_create_id for the $prefix.
I used the 'create_sid' handler in session_set_save_handler and it done all the magic for me.
I could continue to use session_regenerate_id();

function sessionCreateHandler()
{
$prefix = 'bla';
return session_create_id($prefix);
}
To Top