PHP 8.1.28 Released!

Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Opzioni di configurazione della sessione
Nome Default Modificabile Storico dei cambiamenti
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 Disponibile da 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 Disponibile da PHP 7.1.0.
session.trans_sid_hosts $_SERVER['HTTP_HOST'] INI_ALL Disponibile da PHP 7.1.0.
session.sid_length "32" INI_ALL Disponibile da PHP 7.1.0.
session.sid_bits_per_character "4" INI_ALL Disponibile da 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 Rimossa da PHP 7.1.0.
session.hash_bits_per_character "4" INI_ALL Rimossa da PHP 7.1.0.
session.entropy_file "" INI_ALL Rimossa da PHP 7.1.0.
session.entropy_length "0" INI_ALL Rimossa da PHP 7.1.0
Per maggiori dettagli e definizioni sui modi INI_*, vedere Where a configuration setting may be set.

Il sistema di gestione delle sessioni supporta un numero di opzioni di configurazione che si possono inserire nel file php.ini. Di seguito un breve sommario.

session.save_handler string
session.save_handler definisce il nome dell'handler che è utilizzato per salvare e caricare i dati associati alla sessione. Il default è files. Si noti che le singole estensioni postono registrare i propri save_handler; gli handler registrati possono essere ottenuti per una specifica installazione consultando phpinfo(). Vedere anche session_set_save_handler().
session.save_path string
session.save_path definisce l'argomento che è passato all'handler di salvataggio. Se si sceglie l'handler di default files, questo è il percorso in cui i file sono creati. Vedere anche session_save_path().

C'è un argomento N opzionale per questa direttiva che determina il numero di livelli di cartelle su cui verranno distribuiti i file di sessione. Per esempio, impostarlo a '5;/tmp' può portare a creare un file di sessione con questo percorso: /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . Per usare N occorre creare tutte queste cartelle prima dell'utilizzo. Un piccolo shell script è presente in ext/session per eseguire questo lavoro, si chiama mod_files.sh, con una versione per Windows chiamata mod_files.bat. Notare anche che se N è usato ed è maggiore di 0 il garbage collection automatico non sarà eseguito, vedere un php.ini per ulteriori informazioni. Inoltre, se si usa N, assicurarsi di racchiudere session.save_path in "doppie virgolette" poiché il separatore (;) è usato anche per i commenti in php.ini.

Il modulo di salvataggio file crea file utilizzando la modalità 600 di default. Questa impostazione può essere cambiata con gli argomento opzionale MODE: N;MODE;/path dove MODE è la rappresentazione ottale della modalità. L'impostazione MODE non ha effettu sul processo umask.

Avviso

Se questo parametro viene impostato su una cartella leggibile da tutti, come /tmp (il default), altri utenti sul server possono abusare delle informazioni delle sessioni ottenendo la lista dei file in quella cartella.

Attenzione

Quando si utilizza l'argomento opzionale livelli di cartelle N, come descritto sopra, notare che utilizzare un valore più grande di 1 o 2 è inappropriato per la maggior parte dei siti per la grande quantità di cartelle richieste: per esempio, un valore di 3 implica che (2 ** session.sid_bits_per_character) ** 3 cartelle esistano nel filesystem, che può risultare in un sacco di spazio e inode sprecati.

Utilizzare un N maggiore di 2 solo se si è assolutamente sicuri che il proprio sito sia grande abbastanza per richiederlo.

session.name string
session.name specifica il nome della sessione usato come nome del cookie. Dovrebbe contenere solamente caratteri alfanumerici. Il valore predefinito è PHPSESSID. Vedere anche session_name().
session.auto_start bool
session.auto_start specifica se il modulo di sessione inizia automaticamente una sessione al momento della richiesta. Il valore predefinito è 0 (disabilitato).
session.serialize_handler string
session.serialize_handler definisce il nome dell'identificativo usato per serializzare/deserializzare i dati. I formati supportati sono il formato di serializzazione (nome php_serialize), i formati interni di PHP (nome php e php_binary) e WDDX (nome wddx). WDDX è disponibile solo se PHP è compilato con il supporto WDDX . php_serialize è disponibile da PHP 5.5.4. php_serialize utilizza semplici funzioni serialize/unserialize internamente e non ha limitazioni che php e php_binary hanno. Vecchi identificativi per serializzare non possono memorizzare indici numerici o indici di stringhe che contengono caratteri speciali (| e !) in $_SESSION. Utilizzare php_serialize per evitare errori legati agli indici numerici o a caratteri speciali alla chiusura dello script. Il valore predefinito è php.
session.gc_probability int
session.gc_probability in combinazione con session.gc_divisor è usato per gestire la probabilità che la routine gc (garbage collection) venga eseguita. Il valore predefinito è 1. Vedere session.gc_divisor per i dettagli.
session.gc_divisor int
session.gc_divisor in combinazione con session.gc_probability definisce la probabilità che la routine gc (garbage collection) venga eseguita ad ogni inizializzazione di sessione. La probabilità è calcolata usando gc_probability/gc_divisor, es. 1/100 significa che c'è la probabilità del 1% che il processo GC parta ad ogni richiesta. session.gc_divisor ha come valore predefinito 100.
session.gc_maxlifetime integer
session.gc_maxlifetime specifica il numero di secondi dopo i quali i dati verranno visti come 'spazzatura' e potenzialmente ripuliti. La ripulitura (Garbage Collection) avviene durante l'avvio della sessione (in base a session.gc_probability and session.gc_divisor).

Nota: Se differenti script hanno differenti valori di session.gc_maxlifetime ma condividono lo stesso spazio di memorizzazione dei dati di sessione allora lo script con il valore minimo sarà quello che ripulirà i dati. In questo caso, utilizzare la direttiva assieme a session.save_path.

session.referer_check string
session.referer_check contiene la sottostringa che si vuole cercare nel HTTP Referer. Se il Referer è stato inviato dal client e la sottostringa non viene trovata, il session id incorporato viene segnato come non valido. Il valore predefinito è la stringa vuota.
session.entropy_file string
session.entropy_file fornisce il percorso a una resource esterna (file) che sarà usata come una fonte addizionale di entropia nel processo di creazione del session id. Esempi sono /dev/random o /dev/urandom che sono disponibili in molti sistemi Unix. Questa funzionalità è supportata su Winows dalla versione PHP 5.3.3. Impostare session.entropy_length a un valore diverso da zero farà sì che PHP utilizzi come sorgente di entropia la Windows Random API.

Nota: Rimossa in PHP 7.1.0 In PHP 5.4.0 session.entropy_file ha come valore predefinito /dev/urandom o /dev/arandom se è disponibile. In PHP 5.3.0 questa direttiva è lasciata vuota per impostazione predefinita.

session.entropy_length int
session.entropy_length specifica il numero di bytes che saranno letti dal file specificato qui sopra. Il valore predefinito è 32. Rimossa in PHP 7.1.0.
session.use_strict_mode bool
session.use_strict_mode specifica se il modulo userà la modalità "strict session id". Se questa modalità è abilitata, il modulo non accetta ID di sessione non inizializzati. Se il browser invia un ID non inizializzato, un nuovo ID di sessione è inviato al browser. Utilizzato la modalità strict, le applicazioni sono protette da attacchi "session fixation". Il valore predefinito è 0 (disabilitato).

Nota: L'abilitazione di session.use_strict_mode è obbligatoria per la sicurezza generale della sessione. A tutti i siti è consigliato di abilitarla. Per ulteriori dettagli vedere l'esempio di codice di session_create_id().

Avviso

Se un gestore di sessione personalizzato registrato con session_set_save_handler() non implementa SessionUpdateTimestampHandlerInterface::validateId(), nè fornisce la callback validate_sid, rispettivamente, la modalità di ID di sessione rigorosa è effettivamente disabilitata, indipendentemente dal valore di questa direttiva. Da notare in particolare che SessionHandler non implementa SessionHandler::validateId().

session.use_cookies bool
session.use_cookies specifica se il modulo userà i cookie per salvare il session id sul client Il valore predefinito è 1 (abilitato).
session.use_only_cookies bool
session.use_only_cookies specifica se il modulo userà solo i cookie per salvare il session id sul client. L'abilitazione di questa impostazione previene gli attacchi che passano session id nelle URL. Il valore predefinito è 1 (abilitato) da PHP 5.3.0.
session.cookie_lifetime int
session.cookie_lifetime specifica il tempo di vita in secondi del cookie inviato al browser. Il valore 0 significa "finché il browser non viene chiuso". Il valore predefinito è 0. Vedere anche session_get_cookie_params() e session_set_cookie_params().

Nota: Il timestamp di scadenza è impostato relativamente all'orario del server, che non è necessariamente lo stesso di quello del browser.

session.cookie_path string
session.cookie_path specifica il percorso da impostare nel session_cookie. Il valore predefinito è /. Vedere anche session_get_cookie_params() e session_set_cookie_params().
session.cookie_domain string
session.cookie_domain specifica il dominio da impostare nel session_cookie. Il valore predefinito è vuoto, che corridponde al nome dell'host del server che ha generato il cookie, secondo le specifiche dei cookie. Vedere anche session_get_cookie_params() e session_set_cookie_params().
session.cookie_secure bool
session.cookie_secure specifica se i cookie devono essere mandati solo su connessioni sicure. Il valore predefinito è off. Vedere anche session_get_cookie_params() e session_set_cookie_params().
session.cookie_httponly bool
Contrassegna il cookie come accessibile solo attraverso il protocollo HTTP. Questo significa che il cookie non sarà accessibile dai linguaggi di scripting, come JavaScript. Questa impostazione aiuta efficacemente a ridurre i furti di identità attraverso attacchi XSS (anche se non è accettato da tutti i browser).
session.cookie_samesite string
Permette ai server di affermare che un cookie non deve essere inviato insieme a richieste cross-site. Questa asserzione consente agli user agent di mitigare il rischio di perdita di informazioni di cross-origin, e fornisce una certa protezione contro gli attacchi di contraffazione delle richieste cross-site. Notare che questo non è supportato da tutti i browser. Un valore vuoto significa che non verrà impostato alcun attributo del cookie SameSite. Lax e Strict indicano che il cookie non verrà inviato per richieste POST cross-domain; Lax invierà il cookie per richieste GET cross-domain, mentre Strict non lo farà.
session.cache_limiter string
session.cache_limiter specifica il metodo di controllo della cache da usare per le pagine di sessione. Può essere uno dei seguenti valori: nocache, private, private_no_expire o public. Il valore predefinito è nocache. Vedere anche la documentazione di session_cache_limiter() per informazioni sul significato di questi valori.
session.cache_expire int
session.cache_expire specifica il tempo di vita in minuti delle pagine di sessione, non ha effetto se il cache_limiter è nocache. Il valore predefinito è 180. Vedere anche session_cache_expire().
session.use_trans_sid bool
session.use_trans_sid Specifica se il supporto trasparente del sid è abilitato o no. Il valore predefinito è 0 (disabled).

Nota: La gestione della sessione basata sulle URL ha dei rischi di sicurezza maggiori rapportata alla gestione basata sui cookie. Per esempio, gli utenti possono inviare una URL che contiene un ID di sessione attivo ai proprio amici via email oppure gli utenti possono salvare una URL che contiene un ID di sessione nei preferiti ed accedere al sito sempre con lo stesso ID. Da PHP 7.1.0, il percorso URL completo, p.es. https://php.net/, è gestito dalla funzionalità trans sid. In precedenza PHP gestiva solo i percorsi URL relativi. Gli host rewrite target sono definiti da session.trans_sid_hosts.

session.trans_sid_tags string
session.trans_sid_tags specifica quali tag HTML devono essere riscritti per includere l'id della sessione quando il supporto transparent sid è abilitato. Il valore predefinito è a=href,area=href,frame=src,input=src,form= form è un tag speciale. Viene aggiunto <input hidden="session_id" name="session_name"> come variabile del form.

Nota: Prima di PHP 7.1.0, per questo scopo veniva utilizzato url_rewriter.tags. Da PHP 7.1.0, fieldset non viene più considerato un tag speciale.

session.trans_sid_hosts string
session.trans_sid_hosts specifica quali host devono essere riscritti per includere l'id della sessione quando il supporto transparent sid è abilitato. Il valore predefinito è $_SERVER['HTTP_HOST'] Possono essere specificati host multipli con ",", non è permesso nessuno spazio tra gli host. p.es. php.net,wiki.php.net,bugs.php.net
session.sid_length int
session.sid_length permette di specificare la lunghezza della stringa ID della sessione. La lunghezza dell'ID della sessione può essere compresa tra 22 e 256. Il valore predefinito è 32. Se si necessita di compatibilità si può specificare 32, 40, ecc. Un ID di sessione più lungo è più difficile da indovinare. È raccomandato utilizzare almeno 32 caratteri.
Suggerimento

Note di compatibilità: Utilizzare 32 invece di session.hash_function=0 (MD5) e session.hash_bits_per_character=4, session.hash_function=1 (SHA1) e session.hash_bits_per_character=6. Utilizzare 26 invece di session.hash_function=0 (MD5) e session.hash_bits_per_character=5. Utilizzare 22 invece di session.hash_function=0 (MD5) e session.hash_bits_per_character=6. È necessario configurare i valori INI per avere almeno 128 bit nell'ID della sessione. È importante non dimenticare di impostare un valore appropriato a session.sid_bits_per_character, altrimenti si avrà un'ID di sessione più debole.

Nota: Questa impostazione è stata introdotta in PHP 7.1.0.

session.sid_bits_per_character int
session.sid_per_character permette di specificare il numero di bit dei caratteri dell'ID della sessione codificata. I valori possibili sono '4' (0-9, a-f), '5' (0-9, a-v), e '6' (0-9, a-z, A-Z, "-", ","). Il valore predefinito è 4. Più bit porteranno ad un ID della sessione più forte. 5 è il valore raccomandato per la maggior parte degli ambienti.

Nota: Questa impostazione è stata introdotta in PHP 7.1.0.

session.hash_function mixed
session.hash_function permete di specificare l'algoritmo di hashing usato per generare l'ID di sessione. '0' significa MD5 (128 bit) e '1' significa SHA-1 (160 bit).

Da PHP 5.3.0 è possibile anche specificare uno degli algoritmi forniti dall'estensione hash (se è disponibile), come sha512 o whirlpool. Una lista completa degli algoritmi disponibili può essere ottenuta con la funzione hash_algos().

Nota: Questo è stata introdotto in PHP 5. Rimosso in PHP 7.1.0.

session.hash_bits_per_character int
session.hash_bits_per_character permette di definire quanti bit sono memorizzati in ogni carattere quando si converte il dato binario dell'hash in forma leggibile. I valori possibile sono '4' (0-9, a-f), '5' (0-9, a-v), e '6' (0-9, a-z, A-Z, "-", ",").

Nota: Rimosso in PHP 7.1.0.

session.upload_progress.enabled bool
Abilita il monitoraggio dell'avanzamento dell'upload, popolando la varibile $_SESSION. Il valore predefinito è 1, abilitato.
session.upload_progress.cleanup bool
Elimina l'informazione dell'avanzamento non appena tutti i dati POST sono stati letti (es. upload completato). Il valore predefinito è 1, abilitato.

Nota: Si consiglia vivamente di mantenere abilitata questa funzionalità.

session.upload_progress.prefix string
Un prefisso usato nella chiave che contiene l'avanzamento dell'upload all'interno di $_SESSION. Questa chiave verrà concatenata con il valore di $_POST[ini_get("session.upload_progress.name")] per fornire un indice unico. Il valore predefinito è "upload_progress_".
session.upload_progress.name string
Il nome della chiave usata in $_SESSION per conservare l'informazione sull'avanzamento. Vedere anche session.upload_progress.prefix. Se $_POST[ini_get("session.upload_progress.name")] non viene fornito o non è disponibile, l'avanzamento dell'upload non sarà registrato. Il valore predefinito è "PHP_SESSION_UPLOAD_PROGRESS".
session.upload_progress.freq mixed
Definisce la frequenza di aggiornamento dell'avanzamento di upload. Può essere definito in byte (es. "aggiorna l'informazione ogni 100 byte"), oppure in percentuale (es "aggiorna l'avanzamento ogni volta che viene trasferito 1% della dimensione del file). Il valore predefinito è "1%".
session.upload_progress.min-freq int
L'intervallo minimo tra gli aggiornamenti, in secondi. Il valore predefinito è "1" (un secondo).
session.lazy_write bool
session.lazy_write, quando impostato a 1, indica che i dati della sessione sono riscritti solo se ci sono cambiamenti. Il valore predefinito è 1, abilitato.

L'avanzamento dell'upload non viene registrato a meno che session.upload_progress.enabled non sia attivata, e la variabile $_POST[ini_get("session.upload_progress.name")] impostata. Vedere Avanzamento dell'upload di sessione per ulteriori dettagli su questa funzionalità.

add a note

User Contributed Notes 24 notes

up
34
Walerian Walawski - https://w87.eu/
6 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
2
zch1
3 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
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
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
6
hassankhodadadeh at NOSPAM dot gmail dot com
12 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
1
theking2(at)king.ma
1 month 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
1 month 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
2
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
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
11 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
-15
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