PHP 8.3.4 Released!

Configuración en tiempo de ejecución

El comportamiento de estas funciones se ve afectado por la configuración de php.ini.

Opciones de configuración de sesión
Nombre Por defecto Cambiable Historial de cambios
session.save_path "" INI_ALL  
session.name "PHPSESSID" INI_ALL  
session.save_handler "files" INI_ALL  
session.auto_start "0" INI_PERDIR  
session.gc_probability "1" INI_ALL  
session.gc_divisor "100" INI_ALL  
session.gc_maxlifetime "1440" INI_ALL  
session.serialize_handler "php" INI_ALL  
session.cookie_lifetime "0" INI_ALL  
session.cookie_path "/" INI_ALL  
session.cookie_domain "" INI_ALL  
session.cookie_secure "" INI_ALL  
session.cookie_httponly "" INI_ALL  
session.cookie_samesite "" INI_ALL Disponible desde PHP 7.3.0.
session.use_strict_mode "0" INI_ALL  
session.use_cookies "1" INI_ALL  
session.use_only_cookies "1" INI_ALL  
session.referer_check "" INI_ALL  
session.cache_limiter "nocache" INI_ALL  
session.cache_expire "180" INI_ALL  
session.use_trans_sid "0" INI_ALL  
session.trans_sid_tags "a=href,area=href,frame=src,form=" INI_ALL Disponible desde PHP 7.1.0.
session.trans_sid_hosts $_SERVER['HTTP_HOST'] INI_ALL Disponible desde PHP 7.1.0.
session.sid_length "32" INI_ALL Disponible desde PHP 7.1.0.
session.sid_bits_per_character "5" INI_ALL Disponible desde PHP 7.1.0.
session.upload_progress.enabled "1" INI_PERDIR  
session.upload_progress.cleanup "1" INI_PERDIR  
session.upload_progress.prefix "upload_progress_" INI_PERDIR  
session.upload_progress.name "PHP_SESSION_UPLOAD_PROGRESS" INI_PERDIR  
session.upload_progress.freq "1%" INI_PERDIR  
session.upload_progress.min_freq "1" INI_PERDIR  
session.lazy_write "1" INI_ALL  
session.hash_function "0" INI_ALL Eliminado en PHP 7.1.0
session.hash_bits_per_character "4" INI_ALL Eliminado en PHP 7.1.0
session.entropy_file "" INI_ALL Eliminado en PHP 7.1.0.
session.entropy_length "0" INI_ALL Eliminado en PHP 7.1.0.
Para más detalles y definiciones de los modos de INI_*, vea Dónde se puede realizar un ajuste de configuración.

El sistema de administración de sesiones admite varias opciones de configuración que se pueden colocar en el fichero php.ini. Se dará una visión general breve.

session.save_handler string
session.save_handler define el nombre del gestor que se usa para almacenar y recuperar información asociada con una sesión. Por defecto es files. Observe que las extensiones individuales pueden registrar sus propios gestores save_handler; los gestores registrados se pueden obtener a nivel de instalación consultando phpinfo(). Véase también session_set_save_handler().
session.save_path string
session.save_path define el argumento que es pasado al gestor de almacenamiento. Si se elige el gestor de archivos por defecto, éste es la ruta donde los archivos son creados. Véase también session_save_path().

Hay un argumento opcional N para esta directiva que determina el número de niveles de directorios por donde los archivos de sesión se desplegarán. Por ejemplo, establecerlo a '5;/tmp' puede terminar en crear un archivo de sesión y ubicación como /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . Para usar N se deben crear todos estos directorios antes de utilizarlo. Para realizar esto, existe un pequeño script tipo shell en ext/session que se llama mod_files.sh, con una versión de Windows llamada mod_files.bat. Observe también que si N se usa y es más grande que 0 no se llevará a cabo la recolección de basura automática, vea una copia de php.ini para más información. También, si usa N, asegúrese de encerrar session.save_path entre "comillas" ya que el separador (;) también se usa para comentarios en php.ini.

El módulo de almacenamiento de ficheros crea ficheros usando el modo 600 de forma predeterminada. Este valor se puede cambiar con el argumento opcional MODE: N;MODE;/path, donde MODE es la representación octal del modo. Establecer MODE no afecta al proceso umask.

Advertencia

Si se deja esta configuración para un directorio legilble por todo el mundo, tal como /tmp (por defecto), otros usuarios en el servidor pueden ser capaces de secuestrar sesiones obteniendo la lista de archivos de ese directorio.

Precaución

Al emplear el argumento opcional de nivel de directorio N, como está descrito arriba, observe que al utilizar un valor mayor que 1 o 2 no es apropiado para la mayoría de los sitios debido al gran número de directorios requeridos: por ejemplo, un valor de 3 implica que existen 64^3 directorios en el sistema de ficheros, lo que puede resultar en un gran despredicio de escpacio e inodos.

Utilice solamente N con un valor mayor que 2 si está absolutamente seguro de que el sitio es lo suficientemente grande para requerirlo.

session.name string
session.name specifica el nombre de la sesión que se usa como nombre de cookie. Sólo debería contener caracteres alfanuméricos. Por defecto es PHPSESSID. Véase también session_name().
session.auto_start bool
session.auto_start especifica si el módulo de sesión inicia una sesión automáticamente cuando arranque una petición. Por defecto es 0 (deshabilitado).
session.serialize_handler string
session.serialize_handler define el nombre del manejador que se usa para serializar/deserializar datos. El formato de serialización de PHP (nombre php_serialize), formatos de internos de PHP (nombre php y php_binary) y WDDX son admitidos (nombre wddx). WDDX solamente está disponible si PHP está compilado con soporte para WDDX. php_serialize usa internamente una función pura de serialización/deserialización y no tiene las limitaciones que tienen php y php_binary. Los gestores de serialización más antiguos no pueden almacenar índices numéricos ni de string que contengan caracters especiales (| y !) en $_SESSION. Use php_serialize para evitar errores con índices numéricos o caracteres especiales al cierre del script. Lo predeterminado es php.
session.gc_probability integer
session.gc_probability se usa junto con session.gc_divisor para manejar la probabilidad de que la rutina de gc (garbage collection, recolección de basura) está iniciada. Por defecto es 1. Véase session.gc_divisor para más detalles.
session.gc_divisor integer
session.gc_divisor junto con session.gc_probability define la probabilidad de que el proceso de gc (garbage collection, recolección de basura) esté iniciado en cada inicialización de sesión. La probabilidad se calcula usando gc_probability/gc_divisor, p.ej. 1/100 significa que hay un 1% de probabilidad de que el proceso de GC se inicie en cada petición. session.gc_divisor por defecto es 100.
session.gc_maxlifetime integer
session.gc_maxlifetime especifica el número de segundos después de lo cual la información sea vista como 'basura' y potencialmente limpiada. La recolección de basura puede suceder durante el inicio de sesiones (dependiendo de session.gc_probability y session.gc_divisor).

Nota: Si diferentes scripts tienen diferentes valores de session.gc_maxlifetime pero comparten la misma ubicación para almacenar la información de sesión, la información del script con el mínimo valor será limpiada. En este caso use esta directiva junto con session.save_path.

session.referer_check string
session.referer_check contiene la subcadena para comprobar cada HTTP Referer. Si la Referencia fue enviada por el cliente y la subcadena no se encontró, el id de sesión embebido será marcado como no válido. Por defecto es una cadena vacía.
session.entropy_file string
session.entropy_file da una ruta a un recurso externo (archivo) que será usado como una fuente de entropía adicional en el proceso de creación del id de sesión. Ejemplos: /dev/random o /dev/urandom que están disponibles en la mayoría de sistemas Unix. Esta función está disponible en Windows. Si se establece session.entropy_length a un valor que no sea cero hará que PHP use la Windows Random API como fuente entrópica.

Nota: Eliminado en PHP 7.1.0. session.entropy_file usa de forma predeterminada /dev/urandom o /dev/arandom si están disponibles.

session.entropy_length integer
session.entropy_length especifica el número de bytes que serán leídos desde el archivo especificado arriba. Por defecto es 32. Eliminado en PHP 7.1.0.
session.use_strict_mode bool
session.use_strict_mode especifica si el módulo usará el modo de id de sesión estricto. Si este modo está habilitado, el módulo no aceptará IDs de sesioines no inicializados. Si se envia desde el navegador un ID de sesión no inicializado, se envía un nuevo ID de sesión al navegador. Las aplicaciones están protegidas de la fijación de sesiones mediante la adopción de sesión con modo estricto. El valor predeterminado es 0 (deshabilitado).

Nota: Es obligatoria habilitar session.use_strict_mode por seguridad general de sesión. Todos los sitios están advertidos de esto. Véase el código de ejemplo de session_create_id() para más detalles.

Advertencia

Si una sesión personalizada es registrada a través de la función session_set_save_handler() y esta no implementa SessionUpdateTimestampHandlerInterface::validateId(), ni proporciona el callback validate_sid respectivamente, el modo strict session ID es deshabilitado, independientemente del valor de esta directiva. Observe que SessionHandler no SessionHandler::validateId().

session.use_cookies bool
session.use_cookies especifica si el módulo usará cookies para almacenar el id de sesión en la parte del cliente. Por defecto es 1 (habilitado).
session.use_only_cookies bool
session.use_only_cookies especifica si el módulo sólo usará cookies para almacenar el id de sesión en la parte del cliente. Habilitar este ajuste previene ataques que implican pasar el id de sesión en la URL. Por defecto es 1 (habilitado).
session.cookie_lifetime integer
session.cookie_lifetime especifica el tiempo de vida en segundos de la cookie que es enviada al navegador. El valor 0 significa "hasta que el navegador se cierre". Por defecto es 0. Véase también session_get_cookie_params() y session_set_cookie_params().

Nota: La marca de tiempo de caducidad se establece relativa a la hora del servidor, la cúal no es necesariamente la misma que la hora del navegador del cliente.

session.cookie_path string
session.cookie_path especifica la ruta a establecer en la cookie de sesión. Por defecto es /. Véase también session_get_cookie_params() y session_set_cookie_params().
session.cookie_domain string
session.cookie_domain especifica el dominio a establecer en la cookie de sesión. Por defecto es ninguno, significando el nombre de host del servidor que generó la cookie según la especificación de cookies. Véase también session_get_cookie_params() y session_set_cookie_params().
session.cookie_secure bool
session.cookie_secure especifica si las cookies deberían enviarse sólo sobre conexiones seguras. Por defecto es off. Este ajuste fue añadido en PHP 4.0.4. Véase también session_get_cookie_params() y session_set_cookie_params().
session.cookie_httponly bool
Marca la cookie como accesible sólo a través del protocolo HTTP. Esto siginifica que la cookie no será accesible por lenguajes de script, tales como JavaScript. Este ajuste puede ayudar de manera efectiva a reducir robos de indentidad a través de ataques (aunque no está soportado por todos los navegadores).
session.cookie_samesite string
Permite a los servidores afirmar que no se debe enviar una cookie junto con las solicitudes entre sitios. Esta afirmación permite a los user agents mitigar el riesgo de fuga de información, y proporciona cierta protección contra ataques de falsificación de solicitudes entre sitios. Tenga en cuenta que esto no es compatible con todos los navegadores. Un valor vacío significa que no se establecerá ningún atributo de cookie SameSite. Lax y Strict significan que la cookie no se enviará entre dominios para solicitudes POST; Lax enviará la cookie para solicitudes GET entre dominios, mientras que Strict no lo hará.
session.cache_limiter string
session.cache_limiter especifica el método de control de caché usado por páginas de sesión. Puede ser uno de los siguientes valores: nocache, private, private_no_expire, o public. Por defecto es nocache. Vea también la documentación de session_cache_limiter() para informarse sobre lo que significan estos valores.
session.cache_expire integer
session.cache_expire especifica el tiempo de vida en minutos para las páginas de sesión examinadas, esto no tiene efecto para el limitador nocache. Por defecto es 180. Véase también session_cache_expire().
session.use_trans_sid bool
session.use_trans_sid si está habilitado sid transparente o no. Por defecto es 0 (deshabilitado).

Nota: La administración de sesiones basadas en URL tiene riesgos de seguridad adicionales comparada con la administración de sesiones basdas en cookies. Los usuarios pueden enviar una URL que contenga un ID de sesión activo a sus amigos mediante email o los usuarios pueden guardar una URL que contenga una ID de sesión en sus marcadores y acceder a su sitio siempre con el mismo ID de sesión, por ejemplo. Desde PHP 7.1.0, una ruta de URL completa, p.ej. https://php.net/, es manejada por la característa trans sid. Versiones anteriores de PHP manejaban únicamente rutas de URL relativas. Los 'hosts' objetivos de reescritura están definidos por session.trans_sid_hosts.

session.trans_sid_tags string
session.trans_sid_tags especifica cuáles etiquetas HTML son reescritas para incluir el ID de sesión cuando está habilitado el soporte para SID transparente. Las predeterminadas son a=href,area=href,frame=src,input=src,form= form es una etiqueta especial. <input hidden="id_sesión" name="nombre_sesión"> se añade como variable de formulario.

Nota: Antes de PHP 7.1.0, url_rewriter.tags se utilizaba para este propósito. Desde 7.1.0, fieldset ya no se considera una etiqueta especial.

session.trans_sid_hosts string
session.trans_sid_hosts especifica los hosts que se reescriben para incluir el ID de sesión cuando el soporte para SID transparente está habilitado. El predeterminado es $_SERVER['HTTP_HOST'] Se pueden especificar varios hosts mediante ",", y no se permiten espacios entre hosts. P.ej. php.net,wiki.php.net,bugs.php.net
session.sid_length int
session.sid_length permite especificar la longitud de la cadena del ID de sesión. Esta longitud puede estar entre 22 y 256. El valor predeterminado es 32. Si es necesaria compatibilidad se puede especificar 32, 40, etc. Los ID de sesión más largos son más difíciles de adivinar. Se recomienda al menos 32 caracteres.

Nota sobre la compatibilidad: Use 32 para session.hash_func=0 (MD5) y session.hash_bits_per_character=4, session.hash_func=1 (SHA1) y session.hash_bits_per_character=6. Use 26 para session.hash_func=0 (MD5) y session.hash_bits_per_character=5. Use 22 para session.hash_func=0 (MD5) y session.hash_bits_per_character=6. Se deben cofigurar valores INI para tener al menos 128 bits en ID de sesión. No olvide establecer el valor apropiado en session.sid_bits_per_character, de lo contrario se tendrá un ID de sesión más débil.

Nota: Este ajuste se introdujo en PHP 7.1.0.

session.sid_bits_per_character integer
session.sid_per_character permite especificar el número de bits en caracteres de ID de sesión codificados. Los valores posibles son '4' (0-9, a-f), '5' (0-9, a-v), y '6' (0-9, a-z, A-Z, "-", ","). El predeterminado es 4. Cuantos más bits, más fuerte es el ID de sesión. Se recomienda 5 para la mayoría de entornos.

Nota: Este ajuste se introdujo en PHP 7.1.0.

session.hash_function mixed
session.hash_function permite especificar el algoritmo hash utilizado para generar los ID de sesión. '0' significa MD5 (128 bits) y '1' significa SHA-1 (160 bits).

Es posible especificar cualquier algoritmo porporcionado por la extensión hash (si está disponible), como sha512 o whirlpool. Una lista completa de los algoritmos soportados se puede obtener con la función hash_algos().

Nota: Eliminado en PHP 7.1.0.

session.hash_bits_per_character integer
session.hash_bits_per_character permite definir cuántos bits son almacenados en cada carácter cuando se convierte la información hash binaria a algo legible. Los valores posibles son '4' (0-9, a-f), '5' (0-9, a-v), y '6' (0-9, a-z, A-Z, "-", ",").

Nota: Eliminado en PHP 7.1.0

session.upload_progress.enabled bool
Habilita el seguimiento del progreso de subida de ficheros, rellenado la variable $_SESSION. Por omisión su valor es 1, habilitado.
session.upload_progress.cleanup bool
Limpieza de la información del progreso al finalizar la lectura de los datos del POST (p.ej. al finalizar la subida). Por omisión su valor es 1, habilitado.

Nota: Es muy recomendado mantener esta opción habilitada.

session.upload_progress.prefix string
Prefijo usado para la clave del progreso de subida en $_SESSION. Esta clave será concatenada con el valor de $_POST[ini_get("session.upload_progress.name")] para proporcionar un índice único. Por omisión su valor es "upload_progress_".
session.upload_progress.name string
El nombre de la clave a usar en $_SESSION para guardar la información del progreso de subida. Ver también session.upload_progress.prefix. Si no se pasa $_POST[ini_get("session.upload_progress.name")] o no está disponible, el progreso de subida no será grabado. Por omisión su valor es"PHP_SESSION_UPLOAD_PROGRESS".
session.upload_progress.freq mixed
Determina cada cuanto debería actualizarse la información del proceso de subida. Este valor puede ser definido en bytes (p.ej. "actualiza la información del progreso de subida después de cada 100 bytes"), o en porcentajes (p.ej. "actualiza la información del proceso de subida después de recibir el 1% del total del tamaño del fichero"). Por omisión "1%".
session.upload_progress.min-freq integer
El retraso mínimo entre actualizaciones, en segundos. Por omisión su valor es "1" (un segundo).
session.lazy_write bool
session.lazy_write, cuando está establecida a 1, significa que los datos de sesión solamente son rescritos si cambian. El valor predeterminado es 1, habilitado.

El progreso de subida no será registrado a no ser que session.upload_progress.enabled esté habilitado, y la variable $_POST[ini_get("session.upload_progress.name")] esté definida. Ver Session Upload Progress para más información de como funciona.

add a note

User Contributed Notes 25 notes

up
34
Walerian Walawski - https://w87.eu/
5 months ago
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."
# http://php.net/manual/en/session.configuration.php#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
up
77
Christopher Kramer
9 years ago
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 .
up
18
GreenReaper
9 years ago
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.
up
16
info at thimbleopensource dot com
8 years ago
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.
up
1
zch1
2 months ago
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')
up
5
boan dot web at outlook dot com
5 years ago
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.

http://php.net/manual/en/function.session-cache-limiter.php
up
8
Wouter
13 years ago
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)
up
7
jlevene at etisoftware dot com
11 years ago
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
up
7
hassankhodadadeh at NOSPAM dot gmail dot com
11 years ago
max value for "session.gc_maxlifetime" is 65535. values bigger than this may cause php session stops working.
up
2
li-lingjie
6 years ago
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
up
3
Nicholas
13 years ago
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
up
1
theking2(at)king.ma
21 days ago
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.
up
0
theking2(at)king.ma
15 days ago
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
up
-1
usrhlp at yahoo dot com
13 days ago
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.
up
0
ohcc at 163 dot com
6 years ago
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.
up
-1
AskApache
13 years ago
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.
up
-2
00 at f00n dot com
15 years ago
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
up
-2
mikaelkael at php dot net
15 years ago
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'));
up
-3
orbill
13 years ago
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.
up
-4
white-gandalf at web dot de
6 years ago
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.
up
-2
polygon dot co dot in at gmail dot com
2 years ago
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.
up
-1
descartavel1+php at gmail dot com
10 months ago
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
up
-6
sony-santos at bol dot com dot br
15 years ago
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).
up
-16
phpforcharity dot 5 dot pistos at geoshell dot com
15 years ago
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!
up
-21
Anonymous
7 years ago
In response to this comment: http://php.net/manual/en/session.configuration.php#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.
To Top