(PHP 4, PHP 5, PHP 7, PHP 8)
session_id — Получает и (или) устанавливает идентификатор текущей сессии
Функция session_id() получает или устанавливает идентификатор текущей сессии.
Текущее имя и идентификатор сессии в виде строки,
которую можно добавлять в URL-адреса, также получают через константу SID .
Дополнительную информацию об обработке сессий
даёт раздел «Функции для работы с сессиями».
id
Параметр id
заменит идентификатор текущий сессии, если значение аргумента не равно null .
Для этого функцию session_id() вызывают
перед вызовом функции session_start() . Набор символов, которые
разрешается указывать в идентификаторе сессии, зависит от обработчика сессии.
Например, обработчик файлов сессий поддерживает только символы
из диапазона [a-zA-Z0-9,-].
Замечание: Функция session_start() будет отправлять новый блок данных cookie при каждом вызове, если в файле конфигурации включили сессионные cookies и вызвали функцию session_id() с аргументом
id, независимо от того, совпадает ли идентификатор текущей сессии с тем, который устанавливает функция.
Функция session_id() возвращает идентификатор текущей сессии
или пустую строку "", если текущей сессии нет —
идентификатор текущей сессии не существует.
Функция возвращает false , если возникла ошибка.
| Версия | Описание |
|---|---|
| 8.0.0 |
Параметр id теперь принимает значение null .
|
It may be good to note that PHP does not allow arbitrary session ids. The session id validation in PHP source is defined in ext/session/session.c in the function php_session_valid_key:
https://github.com/php/php-src/blob/master/ext/session/session.c
To put it short, a valid session id may consists of digits, letters A to Z (both upper and lower case), comma and dash. Described as a character class, it would be [-,a-zA-Z0-9]. A valid session id may have the length between 1 and 128 characters. To validate session ids, the easiest way to do it use a function like:
<?php
function session_valid_id($session_id)
{
return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}
?>
session_id() itself will happily accept invalid session ids, but if you try to start a session using an invalid id, you will get the following error:
Warning: session_start(): The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'You need to be careful if your page is expected to be accessed via GET requests from a smartphone.
I noticed that when I explicitly (or via JavaScript) refresh a page on my smartphone using Chrome, the browser sends three simultaneous GET requests to get a complete page. In these requests, cookies are reset and the session ID is renewed, which might lead your PHP script to believe that these are new connexions.
I could not determine which criteria the browser uses to decide how many different requests should be sent. However, this does not happen with pages obtained from a POST request.
A word of advice: forms should not use the GET method if their processing involves writing data (database, file, email, etc.), but only if the subsequent actions simply involve reading data.