Настройка во время выполнения

Поведение этих функций зависит от установок в 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_INI_ALL в PHP <= 4.2.3. PHP_INI_PERDIR в PHP < 5. Доступна с PHP 4.0.3.
session.bug_compat_42 "1" PHP_INI_ALL Доступна с PHP 4.3.0. Упразднена в PHP 5.4.0.
session.bug_compat_warn "1" PHP_INI_ALL Доступна с PHP 4.3.0. Упразднена в PHP 5.4.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 Доступна с PHP 5.4.0.
session.upload_progress.cleanup "1" PHP_INI_PERDIR Доступна с PHP 5.4.0.
session.upload_progress.prefix "upload_progress_" PHP_INI_PERDIR Доступна с PHP 5.4.0.
session.upload_progress.name "PHP_SESSION_UPLOAD_PROGRESS" PHP_INI_PERDIR Доступна с PHP 5.4.0.
session.upload_progress.freq "1%" PHP_INI_PERDIR Доступна с PHP 5.4.0.
session.upload_progress.min_freq "1" PHP_INI_PERDIR Доступна с PHP 5.4.0.
Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.

Система управления сессиями поддерживает ряд опций, которые могут быть указаны в файле php.ini. Ниже приводится краткий обзор.

session.save_handler string
session.save_handler определяет имя обработчика, который используется для хранения и извлечения данных, связанных с сессией. По умолчанию имеет значение files. Следует обратить внимание, что некоторые расширения могут зарегистрировать собственные обработчики (save_handler). Текущие зарегистрированные обработчики отображаются в phpinfo(). См. также session_set_save_handler().
session.save_path string
session.save_path определяет аргумент, который передается в обработчик сохранения. При установленном по умолчанию обработчике files, аргумент содержит путь, где будут создаваться файлы. См. также session_save_path().

У этой директивы также существует дополнительный аргумент N, определяющий глубину размещения файлов сессии относительно указанной директории. Например, указание '5;/tmp' может в конечном итоге привести к такому размещению файла сессии: /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . Для того, чтобы использовать аргумент N, необходимо предварительно создать все эти директории. Помочь в этом может небольшой скрипт, расположенный в ext/session. Версия для bash называется mod_files.sh, а Windows-версия - mod_files.bat. Также следует учитывать, что если N определен и больше 0, то автоматическая сборка мусора не выполняется, подробнее см. информацию в файле php.ini. Если используется N, необходимо также удостовериться, что значение session.save_path указано в кавычках, поскольку разделитель (;) в php.ini используется как знак комментария.

Внимание

Если установить в качестве значения общедоступную для чтения директорию, например, /tmp (по умолчанию), остальные пользователи сервера получат возможность перехватить сессию пользователя, получив список файлов такой директории.

Замечание: До версии PHP 4.3.6, для использования механизма сессий пользователям Windows приходилось изменять эту переменную. Необходимо было указать корректный путь, например, такой: c:/temp.

session.name string
session.name определяет название сессии, используемое как название Cookies. Может содержать только цифры и буквы. По умолчанию равно PHPSESSID. См. также session_name().
session.auto_start boolean
session.auto_start определяет, будет ли модуль сессии запускать сессию автоматически при старте. Значение по умолчанию 0 (отключено).
session.serialize_handler string
session.serialize_handler определяет имя обработчика, который используется для сериализации / десериализации данных. В настоящее время используется внутренний формат PHP (наименование php или php_binary), а также поддерживается WDDX (наименование wddx). WDDX доступен только в том случае, если PHP скомпилирован с поддержкой WDDX. Значение по умолчанию: php.
session.gc_probability integer
session.gc_probability в сочетании с session.gc_divisor определяет вероятность запуска функции сборщика мусора (gc, garbage collection). По умолчанию равна 1. См. подробнее в session.gc_divisor.
session.gc_divisor integer
session.gc_divisor в сочетании с session.gc_probability вероятность запуска функции сборщика мусора (gc, garbage collection) при каждой инициализации сессии. Вероятность рассчитывается как gc_probability/gc_divisor, т.е. 1/100 означает, что функция gc запускается в одном случае из ста, или 1% при каждом запросе. session.gc_divisor по умолчанию имеет значение 100.
session.gc_maxlifetime integer
session.gc_maxlifetime задает отсрочку времени в секундах, после которой данные будут рассматриваться как "мусор" и потенциально будут удалены. Сбор мусора может произойти в течение старта сессии (в зависимости от значений session.gc_probability и session.gc_divisor).

Замечание:

Если разные скрипты имеют разные значения session.gc_maxlifetime, но при этом одни и те же места для хранения данных сессии, то скрипт с минимальным значением уничтожит все данные. В таком случае следует использовать эту директиву вместе с session.save_path.

Замечание: Если по умолчанию используется обработчик file, файловая система должна отслеживать время доступа (access time, atime). Windows FAT этого не позволяет, при использовании данной файловой системы (или любой другой без поддержки отслеживания времени доступа) придется разрабатывать собственный способ сборки сессионного мусора. Начиная с версии PHP 4.2.3 используется mtime (modified date, дата изменений) вместо atime. В этом случае поддержка файловой системой atime не требуется.

session.referer_check string
session.referer_check содержит подстроку, которую можно использовать при проверке HTTP Referer. Если клиентом был послан referer и подстрока не была выявлена, то идентификатор сессии будет помечен как недействительный. По умолчанию используется пустая строка.
session.entropy_file string
session.entropy_file содержит путь к ресурсу (файлу), используемому как дополнительный источник энтропии в процессе создания идентификатора сессии. Например, /dev/random или /dev/urandom, которые доступны на многих Unix-системах. Эта возможность также поддерживается в Windows начиная с версии PHP 5.3.3. Указание ненулевого значения в session.entropy_length предписывает PHP использовать в качестве источника энтропии Windows Random API.
session.entropy_length integer
session.entropy_length определяет количество байт, которые будут прочитаны из вышеуказанного файла. По умолчанию 0 (отключено).
session.use_cookies boolean
session.use_cookies определяет, будет ли модуль использовать cookies для хранения идентификатора сессии на стороне клиента. По умолчанию 1 (включено).
session.use_only_cookies boolean
session.use_only_cookies определяет, будет ли модуль использовать только cookies для хранения идентификатора сессии на стороне клиента. Включение этого параметра предотвращает атаки с использованием идентификатора сессии, размещенного в URL. Добавлено в PHP 4.3.0. Значение по умолчанию 1 (включено) с версии PHP 5.3.0.
session.cookie_lifetime integer
session.cookie_lifetime указывает время жизни cookies, отправляемого в браузер клиента, в секундах. Значение 0 означает, что cookies будут валидны до закрытия браузера. По умолчанию равно 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. В соответствии со спецификацией нет смысла дополнительно указывать имя хоста, который сгенерировал cookies. См. также session_get_cookie_params() и session_set_cookie_params().
session.cookie_secure boolean
session.cookie_secure указывает, должны ли cookies передаваться только через защищенное соединение. По умолчанию off. Добавлено в версии PHP 4.0.4. См. также session_get_cookie_params() и session_set_cookie_params().
session.cookie_httponly boolean
Отметка, согласно которой доступ к cookies может быть получен только через HTTP протокол. Это означает, что cookies не будут доступны через скриптовые языки, такие как JavaScript. Данная настройка позволяет эффективно защитить от XSS атак (к сожалению, эта функция поддерживается не всеми браузерами).
session.cache_limiter string
session.cache_limiter определяет метод контроля кэша, используемого для страниц сессий. Может принимать одно из следующих значений: 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 (отключено).

Замечание: В PHP 4.1.2 и более ранних версиях, данная опция доступна при компиляции с --enable-trans-sid. Начиная с PHP 4.2.0, возможность trans-sid всегда доступна. Управление сессией на основе URL имеет дополнительные риски безопасности по сравнению с управлением на основе cookies. В качестве примера можно упомянуть такие ситуации, когда пользователи могут отправить URL, содержащий идентификатор активной сессии своим друзьям по электронной почте или сохранить ссылку с идентификатором в закладках и все время посещать сайт с одним и тем же идентификатором.

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_42 и session.bug_compat_warn.
session.hash_function mixed
session.hash_function позволяет указать алгоритм хэширования, используемый для генерации идентификатора сессии. '0' означает MD5 (128 bits), а '1' означает SHA-1 (160 bits).

Начиная с PHP 5.3.0 также стало возможным указать любой из алгоритмов, предусмотренных расширением hash (если оно доступно), например sha512 или whirlpool. Полный список алгоритмов может быть получен с помощью функции hash_algos().

Замечание:

Эта опция была добавлена в 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, "-", ",").

Замечание:

Эта опция была добавлена в PHP 5.

url_rewriter.tags string
url_rewriter.tags определяет, какие HTML-теги будут переписаны при включении идентификатора сессии при условии включенной поддержки transparent sid. По умолчанию a=href,area=href,frame=src,input=src,form=fakeentry,fieldset=

Замечание: Если необходимо строгое соответствие HTML/XHTML, то следует исключить элемент form из данного списка, а поля формы размещать в тэге <fieldset>.

session.upload_progress.enabled boolean
Включает отслеживание прогресса загрузки файлов и заполнение соответствующей переменной в массиве $_SESSION. По умолчанию равна 1, включена.
session.upload_progress.cleanup boolean
Чистка информации о прогрессе загрузки файлов по завершении обработки POST-данных (т.е. по завершении загрузки). По умолчанию равна 1, включена.

Замечание: Строго рекомендуется не отключать эту опцию.

session.upload_progress.prefix string
Префикс, используемый для ключа прогресса загрузки в массиве $_SESSION. Для обеспечения уникальности данный ключ будет присоединен к значению $_POST[ini_get("session.upload_progress.name")]. По умолчанию равен "upload_progress_".
session.upload_progress.name string
Имя ключа, используемого в массиве $_SESSION, для хранения информации о прогрессе. Смотрите также директиву session.upload_progress.prefix. Если элемент $_POST[ini_get("session.upload_progress.name")] не передан, прогресс загрузки данного файла не будет отслеживаться. По умолчанию равно "PHP_SESSION_UPLOAD_PROGRESS".
session.upload_progress.freq mixed
Определяет частоту обновления информации о прогрессе загрузки. Можно указать значение в байтах (т.е. "обновлять информацию о прогрессе каждые 100 байт") или в процентах (т.е. "обновлять информацию о прогрессе после получения 1% данных от размера файла"). По умолчанию равна "1%".
session.upload_progress.min-freq integer
Минимальная задержка между обновлениями, в секундах. По умолчанию равна "1" (одной секунде).

Настройки track_vars и register_globals влияют на способ хранения и использования переменных сессии.

Прогресс загрузки файлов не будет обрабатываться, если не включена опция session.upload_progress.enabled и не установлена переменная $_POST[ini_get("session.upload_progress.name")]. Подробнее об этом смотрите в главе "Отслеживание прогресса загрузки файлов с помощью сессий".

Замечание:

Начиная с PHP 4.0.3, опция track_vars постоянно включена.

Коментарии

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!
2008-06-24 09:05:58
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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
2008-06-25 09:36:22
http://php5.kiev.ua/manual/ru/session.configuration.html
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).
2008-10-16 14:17:06
http://php5.kiev.ua/manual/ru/session.configuration.html
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'));
2009-01-28 14:50:45
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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)
2010-05-19 06:14:35
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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
2010-08-26 14:08:38
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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.
2010-08-30 08:08:54
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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.
2010-11-11 00:00:19
http://php5.kiev.ua/manual/ru/session.configuration.html
max value for "session.gc_maxlifetime" is 65535. values bigger than this may cause  php session stops working.
2012-03-20 19:42:42
http://php5.kiev.ua/manual/ru/session.configuration.html
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
2013-02-21 03:29:33
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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 .
2014-10-02 16:22:23
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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.
2014-10-14 03:56:36
http://php5.kiev.ua/manual/ru/session.configuration.html
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.
2015-07-19 10:39:18
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
In response to this comment: session.configuration#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.
2016-10-14 17:23:01
http://php5.kiev.ua/manual/ru/session.configuration.html
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.
2017-11-25 18:06:03
http://php5.kiev.ua/manual/ru/session.configuration.html
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.
2017-12-18 07:50:03
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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
2017-12-19 11:20:08
http://php5.kiev.ua/manual/ru/session.configuration.html
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.

function.session-cache-limiter
2019-02-10 14:43:21
http://php5.kiev.ua/manual/ru/session.configuration.html
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.
2021-11-07 22:04:16
http://php5.kiev.ua/manual/ru/session.configuration.html
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
2023-05-16 12:11:18
http://php5.kiev.ua/manual/ru/session.configuration.html
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."
       # session.configuration#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
2023-10-08 16:23:12
http://php5.kiev.ua/manual/ru/session.configuration.html
Автор:
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')
2023-12-20 07:57:51
http://php5.kiev.ua/manual/ru/session.configuration.html
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.
2024-02-26 21:43:37
http://php5.kiev.ua/manual/ru/session.configuration.html
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
2024-03-03 11:39:07
http://php5.kiev.ua/manual/ru/session.configuration.html
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.
2024-03-05 19:26:12
http://php5.kiev.ua/manual/ru/session.configuration.html

    Поддержать сайт на родительском проекте КГБ