PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<session_pgsql_status session_cache_expire>
view the version of this page
Last updated: Wed, 26 Oct 2005

CXXXIV. Funzioni di gestione della sessione

Il supporto delle sessioni in PHP consiste nel mantenere certi dati attraverso accessi successivi.Questo vi dà la capacità di costruire applicazioni più consone alle vostre esigenze e di accrescere le qualità del vostro sito web.

Se avete dimestichezza con la gestione delle sessioni di PHPLIB, noterete che alcuni concetti sono simili al supporto dele sessioni in PHP.

Al visitatore che accede al vostro sito web viene assegnato un id unico, il cosidetto id di sessione. Questo viene registrato in un cookie sul lato utente o è propagato tramite l'URL.

Il supporto delle sessioni vi permette di registrare numeri arbitrari di variabili che vengono preservate secondo richiesta.Quando un visitatore accede al vostro sito, PHP controllerà automaticamente (se session.auto_start è settato a 1) o su vostra richiesta (esplicitamente tramite session_start() o implicitamente tramite session_register()) se uno specifico id di sessione sia stato inviato con la richiesta. In questo caso , il precedente ambiente salvato viene ricreato.

Tutte le variabili registrate vengono serializzate dopo che la richiesta è finita. Le variabili registrate che non sono definite vengono marcate come indefinite. All'accesso successivo, queste non vengono definite dal modulo di sessione fino a quando l'utente non le definisce più tardi.

La configurazione di track_vars e register_globals influenza come le variabili di sessione vengono memorizzate una e più volte.

Nota: In PHP 4.0.3, track_vars è sempre attiva.

Nota: In PHP 4.1.0, $_SESSION è disponibile come variabile globale proprio come $_POST, $_GET, $_REQUEST e così via. $HTTP_SESSION_VARS non è sempre globale, $_SESSION lo è sempre. Per questo motivo, global non dovrebbe essere usato per $_SESSION.

Se track_vars è attiva e register_globals non è attiva, solo i membri dell'array associativo globale $HTTP_SESSION_VARS possono essere registrati come variabili di sessione. Le variabili di sessione ripristinate saranno disponibili nell'array $HTTP_SESSION_VARS.

Esempio 1. Registrare una variabile con track_vars attiva

<?php
if (isset($HTTP_SESSION_VARS['count'])) {
  
$HTTP_SESSION_VARS['count']++;
}
else {
  
$HTTP_SESSION_VARS['count'] = 0;
}
?>

L'uso di $_SESSION (o $HTTP_SESSION_VARS con PHP 4.0.6 o precedente) è raccomandato per sicurezza e leegibilità del codice.Con $_SESSION o $HTTP_SESSION_VARS, non c'è bisogno di usare le funzioni session_register()/session_unregister()/session_is_registered(). Gli utenti possono accedere alla variabile di sessione come a una variabile normale.

Esempio 2. Registrare una variabile con $_SESSION.

<?php
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
  
$_SESSION['count'] = 0;
} else {
  
$_SESSION['count']++;
}
?>

Esempio 3. Resettare una variabile con $_SESSION.

<?php
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);

?>

Se register_globals è attiva, allora tutte le variabili globali possono essere registrate come variabili di sessione e le variabili di sessione saranno ripristinate in corrispondenza delle variabili globali. Dal momento che PHP ha bisogno di sapere quali variabili globali sono registrate come variabili di sessione , gli utenti devono registrare le variabili con la funzione session_register() mentre $HTTP_SESSION_VARS/$_SESSION non ha bisogno di usare session_register().

Attenzione

Se state usando $HTTP_SESSION_VARS/$_SESSION e register_globals non è attiva, non usate session_register(), session_is_registered() e session_unregister().

Se attivate register_globals, session_unregister() dovrebbe essere usata dal momento in cui le variabili di sessione vengono registrate come variabili globali quando i dati di sessione vengono deserializzati. Disattivare register_globals è raccomandato sia per motivi di sicurezza che di prestazione.

Esempio 4. Registrare una variabile con register_globals attiva

<?php
if (!session_is_registered('count')) {
  
session_register("count");
  
$count = 0;
}
else {
  
$count++;
}
?>

Se entrambe track_vars e register_globals sono attivate, allora le variabili globali e le entrate di $HTTP_SESSION_VARS/$_SESSION riporteranno lo stesso valore per variabili già registrate.

Se l'utente usa session_register() pre registrare una variabile di sessione, $HTTP_SESSION_VARS/$_SESSION non avranno questa variabile nell'array fino a che non sarà caricata dall'archivio di sessione.(i.e. fino alla prossima richiesta)

Ci sono due metodi per propagare l'id di sessione:

  • I Cookies

  • Un parametro dell'URL

Il modulo di sessione supporta entrambi i metodi. I cookies sono ottimi, ma dal momento che possono non essere a disposizione (i clients non sono costretti ad accettarli ), non possiamo dipendere da questi. Il secondo metodo incorpora l'id di sessione direttamente negli URL.

PHP ha la capacità di farlo in modo trasparente quando compilato con --enable-trans-sid. Se attivate questa opzione, gli URL relativi saranno modificati per contenere l'id di sessione automaticamente. In alternativa, potete usare la costante Alternatively, you can use the constant SID che è definita, se il client non ha mandato il cookie appropriato. SID può avere la forma di session_name=session_id o può essere una stringa vuota.

L'esempio seguente dimostra come registrare una variabile e come collegare una pagina all'altra correttamente usando SID.

Esempio 5. Contare il numero di accessi di un singolo utente

<?php
if (!session_is_registered('count')) {
  
session_register('count');
  
$count = 1;
}
else {
  
$count++;
}
?>

Salve visitatore , hai visitato questa pagina <?php echo $count; ?> times.<p>;

<?php
# il <?php echo SID?> (<?=SID?> può essere usato se short tag è attivo)
# è necessario per preservare l'id di sessione
# nel caso incui l'utente abbia disattivato i cookies
?>

Per continuare, <A HREF="nextpage.php?<?php echo SID?>">clicca qui</A>

Il <?=SID?> non è necessario, se --enable-trans-sid è stato usato per compilare PHP.

Nota: Gli URL non relativi si presume che puntino a siti esterni e quindi non hanno il SID , perchè sarebbe rischioso per la sicurezza propagare il SID a un altro server.

Per implementare l'archiviazione in database , o qualsiasi altro metodo di archiviazione, avete bisogno di usare session_set_save_handler() per creare un set di funzioni di archiviazione a livello utente.

Il sistema di gestione delle sessioni supporta un numero di opzioni di configurazione che potete posizionare nel vostro file php.ini. Ne daremo una breve spiegazione.

  • session.save_handler definisce il nome dell'handler che è usato per archiviare e rilasciare i dati associati a una sessione. Di default è files.

  • session.save_path definisce l'argomento che è passato all'handler di sessione. Se scegliete handler files di default , questo è il percorso dove i files vengono creati. Di default è /tmp. Se la profondità del percorso session.save_path è più di 2, l'accumulo (gc) non sarà effettuato.

    Avvertimento

    Se lasciate questo settato a directory leggibile da tutti , come If you leave this set to a world-readable directory, such as /tmp (il default), altri utenti sul potrebbero essere in grado di dirottare le sessioni prendendo la lista dei files in quella directory.

  • session.name specifica il nome della sessione che è usata come nome del cookie. Dovrebbe contenere solo caratteri alfanumerici. Di default è PHPSESSID.

  • session.auto_start specifica se il modulo di sessione inizia una sessione automaticamente su richiesta iniziale. Di default è 0 (disattivata).

  • session.cookie_lifetime specifica il tempo di vita insecondi del cookie che viene mandato al browser. Il valore 0 significa "fino a che il browser viene chiuso". Di default è 0.

  • session.serialize_handler definisce il nome dell'handler che è usato per serializzare/deserializzare i dati. Al momento, un formato interno di PHP(nome php) e WDDX è supportato (nome wddx). WDDX è solo disponibile, se PHP è compilato con WDDX support. Il defailt è php.

  • session.gc_probability specifica la probabilità , in percentuale ,che la routine gc (garbage collection) sia cominciata ad ogni richiesta in percentuale. Di default è 1.

  • session.gc_maxlifetime specifica il numero di secondi dopo i quali i dati saranno considerati 'spazzatura' e cancellati.

  • session.referer_check contiene la sottostringa con cui volete controllare ogni HTTP referer. Se il referer è stato mandato dal client e la sottostringa non è stata trovata, l'id incorporato nella sessione verrà marcato come non valido. Il default è una stringa vuota.

  • session.entropy_file dà un percorso a una risorsa esterna (file) che sarà usata come una addizionale sorgente entropica nella crazione dell'id di sessione. Esempi sono /dev/random o /dev/urandom che sono disponibili sulla maggior parte dei sistemi Unix.

  • session.entropy_length specifica il numero di bytes che saranno letti dal file specificato sopra. Di default è 0 (disattivato).

  • session.use_cookies specifica se il modulo userà i cookies per archiviare l'id di sessione sul lato client. Di default è 1 (attivo).

  • session.cookie_path specifica il percorso da stabilire in session_cookie. Di default è /.

  • session.cookie_domain specifica il dominio settato in session_cookie. Di default è niente.

  • session.cache_limiter specifica il metodo di controllo della cache da usare per le pagine di sessione (none/nocache/private/private_no_expire/public). Di default è nocache.

  • session.cache_expire specifica il tempo-di-vita , in minuti , delle pagine nella cache, questo non ha effetto sul limitatore nocache. Di default è 180.

  • session.use_trans_sid specifica se il supporto sid trasparente è attivato o no se attivato compilandolo con --enable-trans-sid. Di default è 1 (attivo).

  • url_rewriter.tags specifica quali html tags sono riscritti per includere l'id di sessione se il supporto sid trasparente è attivato. Di default è a=href,area=href,frame=src,input=src,form=fakeentry

Nota: L'handling di sessione è stato aggiunto in PHP 4.0.

Sommario
session_cache_expire -- Ritorna il valore corrente di scadenza della cache
session_cache_limiter -- Assume o imposta il limitatore di cache corrente
session_commit -- Alias di session_write_close()
session_decode -- Decodifica i dati di sessione da una stringa
session_destroy -- Distrugge tutti i dati registrati in una sessione
session_encode --  Codifica i dati della sessione corrente in una stringa
session_get_cookie_params --  Restituisce i parametri del cookie di sessione
session_id -- Assume o imposta l'id di sessione corrente
session_is_registered --  Scopre se una variabile è registrata nella sessione
session_module_name -- Assume o imposta il corrente modulo di sessione
session_name -- Dà e/o stabilisce il nome della sessione corrente
session_regenerate_id --  Update the current session id with a newly generated one
session_register --  Registra una o più variabili con la sessione corrente
session_save_path -- Assume o stabilisce il percorso di salvataggio sessione corrente
session_set_cookie_params --  Imposta i parametri del cookie di sessione
session_set_save_handler --  Imposta le funzioni di archiviazione sessioni a livello utente
session_start -- Inizializza i dati di sessione
session_unregister --  Deregistra una variabile dalla sessione corrente
session_unset --  Libera tutte le variabili di sessione
session_write_close -- Scrive i dati di sessione e termina la sessione


add a note add a note User Contributed Notes
Funzioni di gestione della sessione
phpkloss at wholewheatradio dot org
22-Feb-2006 09:57
If you're having trouble with unset($_SESSION[$something]) working, here's what I discovered (Win2K/PHP 5.x.x).  Assume you want to step through $_SESSION and delete (i.e. unset) certain elements.  So,

foreach ($_SESSION as $key=>$value) {
   if (stristr($key,'something_to_delete')) {
     echo "Will unset $key that has value of $value";
     unset($_SESSION[$key]);
}

What I found was that although the $_SESSION elements were deleted in memory, the actual session file was not being written out with the changes (even after using session_write_close).  What fixed it for me was to COPY $_SESSION INTO A DUMMY ARRAY, THEN STEP THROUGH THAT DUMMY ARRAY TO FIGURE OUT WHICH ELEMENTS OF THE REAL $_SESSION TO DELETE.  I.e.

foreach($_SESSION as $key=>$value) {
  $dummy[$key]=$value;  // copy to a dummy array
}

foreach ($dummy as $key=>$value) {
   if (stristr($key,'something_to_delete')) {
     echo "Will unset $key that has value of $value";
     unset($_SESSION[$key]);
}

It appears that as you're stepping through the actual $_SESSION array in a foreach, if you unset elements of it, those changes won't be recorded to the session disk file.

'Course then again, my coffee is running low so I could be wrong.  But hopefully it's something others can try who might be having a similar problem.
rciq at tlen dot pl
22-Feb-2006 01:08
Don't do anything like:

$_SESSION = $some_array;

My php5.0.4 session stops without saving after such operations.
20-Feb-2006 07:21
In response to "djohnson at jsatech dot com", posted 09-Dec-2005 09:00

"Be warned, when working with tab-based browsers like Opera and Firefox, sessions are preserved across tabs....IE deals with sessions just fine.  There is probably some way to adjust the settings in Firefox or Opera, but that is not the default, and will affect most users."

In fact, the way sessions are managed among different browsers is not all that different among MSIE and Opera and Firefox.  You will find that MSIE sessions can be maintained across browser windows, just like in FF or Opera.  However the difference that djohnson noted is because of the way MSIE windows are created vs FF and Opera.

If you choose, in MSIE, "File->New Window", you will find that PHP sessions are preserved from browser window to browser window.

If, OTOH, you start a new window of MSIE using the start menu or desktop icon, a new instance of MSIE, with a new process ID, is started.  *This* instance does not have anything to do with any other previously existing MSIE instances, and, thus, PHP sessions started in this new MSIE process are distinct from PHP sessions in existing MSIE instances.

See the difference?

Whereas FF and Opera apparently always start a new window into an existing FF or Opera process.  Thus PHP sessions are always maintained across browser instances with FF and Opera.
hans at nieser dot net
14-Feb-2006 04:15
FreeBSD users, instead of modifying the PHP5 port Makefile, you can either install the session extension using the www/php5-session port, or you can install several extensions at once (you can pick them from a menu) using the lang/php5-extensions port. Same goes for PHP4
just_somedood at yahoo dot com
01-Feb-2006 06:31
If you're running FreeBSD, and installed php5 (have not checked 4) from the ports, and are getting errors saying the session functions are undefined, try running phpinfo().  You'll probably see that the '--disable-all' configure command was used.  To fix, edit the /usr/ports/lang/php5/Makefile, and remove the '--disable-all' line.  In that directory, run a 'make deinstall', if you installed already.  Next, run 'make install' while still in that same directory.  It should work fine after that.
warkangaroo
26-Jan-2006 05:33
After hitting my head on the desk a few times trying to debug this construct,

$_SESSION['result']['number'] = $blah;

returning the warning,

"Warning: Cannot use a scalar value as an array"

and not saving my value, I found out that apparently $_SESSION['result'] is a reserved variable... I changed it to $_SESSION['bresult'] and it works fine.

Just trying to save someone a headache...
james dot ellis at gmail dot com
26-Jan-2006 09:23
If you are wondering why your garbage cleanup method is not being called, read on.

The manual notes for garbage cleanup state that the session.gc_divisor defaults to 100:

[code]
//http://php.net/manual/en/ref.session.php
session.gc_probability  ... Defaults to 1.
session.gc_divisor  .... session.gc_divisor defaults to 100.
[/code]

This would provide a gc probability of 1 in 100 ie. your garbage cleanup is going to be called 1% of the time.

Conversely, my PHP 5.1.1 install, compiled from source, contains this in the php.ini-recommended file (and my php.ini file):
[code]
; Define the probability that the 'garbage collection' process is started
; on every session initialization.
; The probability is calculated by using gc_probability/gc_divisor,
; e.g. 1/100 means there is a 1% chance that the GC process starts
; on each request.

session.gc_probability = 1
session.gc_divisor    = 1000
[/code]

A 0.1% probability by default. Based on the information provided, I set my gc_probability to 100,  thus providing a 1% probability stale sessions would be culled.

Moral:your local php.ini may differ from what the manual provides.
jerry dot walsh at gmail dot com
24-Jan-2006 03:56
If you're using sharedance to distributed php sessions across a group of machines beware of the following:

On a freebsd 6.x system I have observed a huge performance hit caused by dns/host file lookups.

To ensure maximum performance using sharedance you should set the 'SESSION_HANDLER_HOST' constant to an IP rather than a hostname.

When i did this my requests per second jumped from 55 to 389 requests per second!
darkelf79 at gmail dot com
21-Jan-2006 12:00
If you set the session_id through the calling URL, it *will not* set the session cookie in 4.4.2.

For example:

www.example.com/?PHPSESSID=foo

This will set the session id to 'foo' but it won't actually set the session cookie. The last known version I'm aware of is 4.3.3 where it will set the cookie.

This doesn't appear to be definitively mentioned in here anywhere. But according to the devs, it's not a bug. Hopefully this knowledge will help you out if you're experiencing the same problem.
pascal.fr => gmail.com
20-Jan-2006 11:24
If you have saved an object in session, you must define the class of the object before the session_start().
If you don't do that, php will not know the class of the object, and his type will be "__PHP_Incomplete_Class".

This:
<?php
session_start
();

class
Foo{
   var
$fooVar = 'Hello world !!!';
}

$myFoo = new Foo();
$_SESSION['myFoo'] = $myFoo;
echo
'Save in session';
?>
define the Foo class and save an instance  in session.

<?php
session_start
();

echo
'<pre>';
  
print_r( $_SESSION ); // don't know the Foo class...
echo '</pre>';
?>

will print :

Array
(
   [myFoo] => __PHP_Incomplete_Class Object
       (
           [__PHP_Incomplete_Class_Name] => foo
           [fooVar] => Hello world !!!
       )

)
royappa at spiralfx dot com
16-Jan-2006 10:19
This is just to note that I was able to fix my problems due to the many helpful comments here.

The problem I was having was as follows:
a) I was dynamically generating a file to download
b) When the user clicked "Save" in MSIE, and then imported the download file into the application, all was well.
c) When the user clicked "Open" to directly import the file, the application would throw an error.

I believe what was happening is that the browser was not saving a local copy of the file due to the "no-store" directive, when the user clicks "Open" directly.

Therefore the examples above regarding pragma & cache-control were useful to resolving it.

Thanks for all the help. I just want to add also that the following web page was of great help to see the actual HTTP headers being sent by the web app: http://www.rexswain.com/httpview.html

Much easier than doing telnet to port 80! Hope this helps other also.   

Andrew Royappa
Ravi Chotalia
27-Dec-2005 04:12
In answer to..
-PHP SESSIONS NOT WORKING in with windows---
...solution on the session cookie path.
I am running Apache 2 and PHP 4.4.0 on a Windows XP SP2.
...
----------------------------------

It was a small mistake in my directory stucture,

I have changed from c:\temp to c:\Temp as I had directory called "temp" not "Temp".Now session is working properly in my case.

Make sure directory name is same, in windows environment too.
marou at marou dot com
22-Dec-2005 05:49
In reponse to fondman at hotmail dot com with the 4.4.0 issue with local variables replacing session variables.

It also happens in 4.4.3. 

I have a development environment set up with 5.0, and the production environment is 4.4.3.  I had set some local variables with the same name as one of my session variables.  It did the same thing you described on the production box, yet worked fine in development.

Just an FYI.
jazfresh at hotmail dot com
20-Dec-2005 03:55
The vanilla implementation of session will blindly spew back the value of the session_id that the user sends it after URL decoding it. This can be used as an attack vector, by including strings like "%0D%0ALocation:%20http://someothersite.com/" in the cookie. Never trust user input, always cleanse it. If you only expect alphanumerics in the session hash, reject any session_id that doesn't contain it.

<?php
if(!preg_match('#^[[:alnum:]]+$#', $_COOKIE['session_id'])) {
  unset(
$_COOKIE['session_id']);
}
session_start();
?>
Florian Sievers
11-Dec-2005 08:51
In addition Firefox doesn't only handel the session over differnet tabs it also do this if you open a new window. So you can work with the same session in different windows and different tabs.
djohnson at jsatech dot com
09-Dec-2005 05:00
Be warned, when working with tab-based browsers like Opera and Firefox, sessions are preserved across tabs.  These can be  either a good thing or bad thing, depending upon your application.  We found this to be problem, if we wanted to log in as two different users in two different tabs.  This is not possible: either the second tab will have the information from the first, or logging into the second will replace the information in the first tab. 

If you close a tab, the session is still persistent. Only when you close the window will the session information be deleted from the browser cache.  IE deals with sessions just fine.  There is probably some way to adjust the settings in Firefox or Opera, but that is not the default, and will affect most users.
bgshea at gmail dot com
04-Dec-2005 10:18
to johnlonely at gmail dot com

the sesion.cookie_path should be used for cookie security. The cookie_path is the path on the server for which the cookies are valid.

i.e. www.example.dom/mywepage/

if cookie_path="/mywebpage"

then

www.example.dom/someonespage/

will not have access to them. I use this parameter without problems.

I'm not saying that this will make cookies secure, but certainly others of www.example.dom will not have access to them.

However, if you have other directories say www.example.dom/niftystuff that you want the cookie to be valid for, then cookie_path needs to be "/".

This is better for servers that use the /~user/ user aliasing.
jodybrabec at yahoo dot com
30-Nov-2005 12:50
To stop PHPSESSID from appearing in the url, try inserting these two lines just before session_start() --
ini_set("url_rewriter.tags","");
ini_set(?session.use_trans_sid?, false);
djhoma at gmail dot com
26-Nov-2005 12:39
As the reference mentions the value of the register_globals variable can cause some problem if you use sessions for verification.
If GET variables are registered as global and you check whether the user is already logged in like this:
<?php
if ($_REQUEST['password'] == "right_password") {
$password = true;
session_register('password');
}
//...later on:
if ($password) {
//secure content
}
?>
Notice, that if you guess the name of the verification variable and pass it through the URL (index.php?password=true) and the register_globals is true then a script like this lets you in.
I know this is a stupid mistake, but maybe I am not the only one who made it...
So after you registered the $password var, you should check the login with session_is_registered() function:
<?php
if (session_is_registered('password')) {
//secure content
}
?>
This function cannot be fooled by GET or POST variables...

Hope it's a useful note!
jounier at ac-bordeaux dot fr
24-Nov-2005 10:35
It took me long to understand how the SID was passed when cookies are disabled, and session.use_trans_sid set to 1.
The doc says it passes through the URL, which is true, when there's no form in the page. In that case, you can see the SID in the URL.
If the page contains a form, PHP automaticaly adds a hidden field it uses to pass the SID by POST. In that case, the SID is invisible in the URL.
Hope it helps.
Bram
19-Nov-2005 05:39
I just noticed that it's possible to access the same session through multiple apache virtual hosts.
So keep this in mind when using sessions for anything sensitive, and make sure to encrypt the data (using the mcrypt functions for example, when available).
Lachlan Hunt
10-Nov-2005 03:10
> Note:  The arg_separator.output  php.ini directive allows to customize the argument seperator. For full XHTML conformance, specify &amp; there.

Exactly the same rule applies to HTML as well, there is abolutely no reason why this should not be set to &amp; by default.  The only difference is that in XHTML, XML error handling defines that it's a well formedness error.  For HTML, error handling was not so well defined nor sanely implemented and tag soup parsers just accept it, but that doesn't make it right.

arg_separator.output *MUST* be set to either of these if you're outputting either HTML or XML:

arg_separator.output = "&amp;"
arg_separator.output = ";"

http://www.w3.org/QA/2005/04/php-session
webmaster at vampirerave dot com
06-Nov-2005 08:27
If you want to receive the functionality of session.use_only_cookies but are using a PHP version prior to 4.3.0, here's an easy way:

if (isset($_GET['PHPSESSID'])) {
  exit;
}

This assumes:

session.name = PHPSESSID

Is set in /etc/php.ini
Armando Scribano armando at scribano dot com dot ar
25-Oct-2005 08:21
//PROTEC YOUR FILES . Double CHECK

User validation login
the basic operation

login.php
<?php
//f_login save a session with user and pass
$login = f_login($_REQUEST['usuario'],$_REQUEST['clave']);
//f_login return a encrypted value
if($login)
{
 
$_SESSION['login_enc']=$login;
}else{
 
//incorrect user or password.
}
?>

protected.php
<?php
//Protected page
//check

//1 CHECK. user and password
//return encrypted session
$enc_user = f_encuser($_SESSION['usuario'], $_SESSION['clave']);

//2 CHECK the last encrypted login and compare
if($_SESSION['login_enc']==$enc_user){
 
// correct
}else{
 
// incorrect
}
?>
christopher dot klein at ecw dot de
24-Oct-2005 08:26
If you have trouble with Internet Explorer 6 and non-working sessions (all session-data is lost after clicking on a link), please look user-hints for setcookie().
You have to add the following line after session_start() to get sessions working:

<?php
 
// Initalize session
 
session_start();
 
// Send modified header
 
header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
?>
lassial at hotmail dot com
23-Oct-2005 04:54
If you would like to ensure your sessions with referer checking you must use iniset() regularly, as

"session.referer_check contains the substring you want to check each HTTP Referer for"

so there is no way PHP can automatically know which URL you are expecting, e.g. it does not assume SCRIPT_NAME or anything else.

I had a serious problem when I tried to disable referer checking with session.referer_check = 0 which of course does not work
johnlonely at gmail dot com
12-Oct-2005 08:32
Everytime I upgrade PHP to a new version, I used to recompile the php.ini file. Everytime I create a website, I always kept the php.ini file so that in the future I would be able to retrieve some Unique properties of the php version I used. So the last php version I've seen where session is sticking is version 4.2. I've been trying for two days with no luck searching the manual and forum, when I tried something :

If you guys always fill the
session.cookie_path = /
to somewhere you the cookies should go, then leave the fuss. You'll save two days! Leave it be!

[Session]
session.cookie_path = /

Happy sticking sessions.
jmoore at sober dot dk
06-Oct-2005 04:54
The documentation says that sessions "may" be readable by other users on the system, but since it is so trivial to do, "are readable" is a more accurate statement.

For example, this will display the contents of all sessions:

<?php

  exec
("cat /tmp/sess_*", $aOutput);
 
print_r($aOutput);

?>

Note: Changing sessions to use a directory other than /tmp will be harder to find, but no more secure.
akoma at t3 dot rim dot or dot jp
19-Sep-2005 12:50
If your are using UTF-8, make sure your source
code editor to do not put the BOM mark
(unicode sign) at the top of your source code. so
it is sent before session_start() causing "headers
already sent" message on httpd error log.
vincent at bevort dot com
14-Sep-2005 02:26
---PHP SESSIONS NOT WORKING---
addition to fasteddie's solution on the session cookie path.
I am running Apache 2 and PHP 4.4.0 on a Windows XP SP2.

Had the same problem that the cookies are saved, in my case att c:\\tmp, but not recognized at reload of the page. The session.save_path must also be set to blank.
The cookies are stored in c:\\windows\\temp.
So if You do not have activated the garbage collector You can find them there for cleanup and error solving.
php at stevegiller dot co dot uk
07-Sep-2005 11:13
If you want prevent people directly setting, for example, a logged_in session variable to bypass your checks using the url?logged_in=true system, a quick trick is to try the line

if (isset($_GET['logged_in'])) { die("Are you trying to take the mickey?"); }

before you do anything else.
I've not tested this heavily, but I'd value any discussion of its merits and potential flaws ...
henry at teddystoo dot com
01-Sep-2005 03:57
Make sure HTTP_HOST matches the url you are using on the browser. (Fix the Apache ServerName setting).
Otherwise, after saving a completed session, the next page will start a new empty session!
fasteddie at byu dot edu not_this_part
17-Aug-2005 05:43
I hope this helps someone:
---PHP SESSIONS NOT WORKING---
My sessions wouldnt ever load from disk. The sessions would start just fine, and a session file would be created and written to disk. (BTW, I'm on a win XP box, Apache 2.0.54, PHP version 5.0.4.) However, next time I loaded the page, the old session would not be used. Instead, a NEW session was created. For me, this happened no matter what computer I was using, whether it was the server (localhost) or a client (remote). A new session was created EVERY TIME I loaded the page.. it was annoying. After a few hours of googling, I gave up and decided to mess around in the php.ini file. I changed this line:
session.cookie_path = /
to this:
session.cookie_path =

Now, php sessions are loaded properly.

I havent tried many things but I think maybe it is because windows needs backslashes (\) instead of forward slashes (/), and if you just leave it blank, it turns out ok.
jphansen at uga dot edu
09-Aug-2005 02:19
I found the easiest method of saving and restoring a user's session data was storing $_SESSION to a database:

<?
addslashes
(var_export($_SESSION, TRUE))
?>

Then restoring it using eval():

<?
eval("\$_SESSION = $session;");
// $session = the first line of code above
?>

Without eval(), $_SESSION = $session would have resulted in $_SESSION being a string instead of an array.
artistan at cableone dot net
09-Aug-2005 07:29
I rewrote adodb's session management class to work across servers with database managed sessions.  Take a look at http://phplens.com/lens/lensforum/msgs.php?id=13428
Christian Boltz <php-manual at cboltz dot de>
28-Jul-2005 01:33
Another note about session.bug_compat_42 and bug_compat_warn.

[full error message:
   "Your script possibly relies on a session side-effect which existed
   until PHP 4.2.3. Please be advised that the session extension does
   not consider global variables as a source of data, unless
   register_globals is enabled. You can disable this functionality and
   this warning by setting session.bug_compat_42 or
   session.bug_compat_warn to off, respectively."
]

The following short script causes the bug_compat_42 warning to appear.

<?php
  session_start
();
 
$_SESSION['var'] = NULL;
 
$var = "foo";
?>

It took me an hour to find out this :-(  - so I post it here to avoid
that more people need such a long time.

Conclusion and test results:

You'll get this warning if $_SESSION['var'] contains NULL and you assign
anything (except NULL) to the global variable $var.

The warning will _not_ appear:
- if $_SESSION['var'] contains anything else  - or -
- if you don't use a global variable named $var
cenaculo at netcabo dot pt
24-Jul-2005 09:09
A quick answer to jentulman at NOSPAM dot jentulman dot co dot uk about the redirecting problem with sessions:
Use session_write_close before redirection thus ensure session data is correctly saved before redirection.
It worked for me in all situations of redirection.
d43m0n at shaw dot ca
18-Jul-2005 10:19
Hello,

I posted earlyer about a issue/bug with Windows servers handling sessions. If you did not read it, it was based on the fact that if you can use ini_set to re-define the session.save_path to a relitive location. PHP will instead use it as the exact location with out looking at the directory where your script is bein execute, thus to say, the session file is not created, or re-read. This of course only occurs if you use <?php reregister_id() ?>. This function is told to open the requested session file, obtain the varibles, regenerate an id for that session, create the new session file and then send the cookie header to the client, of course I did not create this function, so it may not be in that order.

The following code will generate the error that I speak of, and will not successfully generate the new session id, of course like I said above, this only accours on PHP 5 & 5.0.4 under the Windows Environment.

<?php

  define
("_PATH_TMP", "./tmp");
 
ini_set('session.save_path', _PATH_TMP);
 
session_start();
 
$_SESSION['sid']['obsolete'] = session_id();
 
session_regenerate_id();
 
$_SESSION['sid']['replaced'] = session_id();
 
print_r($_SESSION);

?>

(I know that PHP may use defined constants that include '_' characters at the beggining, if it has not already, but I am taking that chance atm...)

This can simply be resolved by using the following code:

<?php
  define
("_PATH_TMP", dirname($_SERVER['SCRIPT_FILENAME']) . "/tmp");
 
ini_set('session.save_path', _PATH_TMP);
 
session_start();
 
$_SESSION['sid']['obsolete'] = session_id();
 
session_regenerate_id();
 
$_SESSION['sid']['replaced'] = session_id();
 
print_r($_SESSION);
?>

As you can see it uses the uses the servers environment to assurtain the exact location to the script, then locates the next root directory of it, and then allows you to define the tmp directory.

* Of course, you dont need to use a tmp directory, and this issue only occurse when using subdirectorys, I found that the following works just aswell, but this did not fit my needs!

<?php

  define
("_PATH_TMP", "./");
 
ini_set('session.save_path', _PATH_TMP);
 
session_start();
 
$_SESSION['sid']['obsolete'] = session_id();
 
session_regenerate_id();
 
$_SESSION['sid']['replaced'] = session_id();
 
print_r($_SESSION);

?>
jphansen at uga dot edu
14-Jul-2005 07:10
If you name a variable the same name as a $_SESSION array and initialize it from a $_REQUEST variable, the $_SESSION array will assume that value, too.

Example:
<?
$_SESSION
["alphabet"] = array('a', 'b', 'c');
var_dump($_SESSION["alphabet"]); // array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }
$alphabet = $_REQUEST['bleh']; //null
var_dump($_SESSION["alphabet"]); // NULL
?>
jentulman at NOSPAM dot jentulman dot co dot uk
12-Jul-2005 10:40
Here's one for the 'session disapearing after a rediredt problem'. It's nice and simple but drove me mad for a couple of hours.
I was getting reports of users logging in apparently successfully but not actually being logged in and couldn't replicate it myself.
I had a configuration file called at the begining of my script setting defines for physical and url paths, and users with the problem were coming in on a domain alias so of course the login went fine, but then they were redirected to a different domain and the cookie was pointless.
Not very technical I know but maybe it'll stop someone having to headbang like I did.
gholyoak at courtdean dot com
22-Jun-2005 05:09
Problems with IE and Content Advisor.

It maybe obvious to some, but as its taken me over a week to sort this out, I will post it here.

If you have Content Advisor enabled in IE, it appears to quietly add an extra GET HTTP request to the root of your website.

This will get processed by your default document, so if your default document is index.php, every legitimate request will be immediately followed by another hit to index.php with a blank query string.

If you increment something in a session, it will be the second hit that has the highest value, but the browser is showing the results of the first GET.

Its easy to see, just add a mail('youremail@address.com') at the start of your default document, turn on content advisor and see how many emails you get !

I have generated a 'pics-label' and added to the META tags on every page and this appears to make IE happy.

You can get a pics-label at www.icra.org.

Hope this helps
ng4rrjanbiah at rediffmail dot com
19-Jun-2005 08:37
The note regarding url_rewriter.tags and XHTML conformity in the manual is bit confusing; it's applicable only when we use <fieldset> tags. Refer http://bugs.php.net/13472

HTH,
R. Rajesh Jeba Anbiah
nigelf at esp dot co dot uk
16-Jun-2005 01:52
Session data is not available to an object's __destruct method as sessions are closed before the object is 'destroyed'.
Richard [at] postamble [dot] [co] [uk]
14-Jun-2005 04:44
Having to use transparent on a system where trans_sid was not compiled, I came up with the folowing ob_start handler:
<?php
function ob_sid_rewrite($buffer){
  
$replacements = array(
      
'/<\s*(a|link|script)\s[^>]*(href|src)\s*=\s*"([^"]*)"/',
      
'/<\s*(a|link|script)\s[^>]*(href|src)\s*=\s*\'([^\'<>]*)\'/',
       );
        
  
$buffer = preg_replace_callback($replacements, "pa_sid_rewriter", $buffer);

  
$buffer = preg_replace('/<form\s[^>]*>/',
      
'\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
      
   return
$buffer;
}

function
pa_sid_rewriter($matches){
  
$buf = $matches[0];
  
$url = $matches[3];
  
$url_orig=$url;
   if (
$url[0]=='/' || $url[0]=='#' || preg_match('/^[A-Za-z0-9]*:/', $url))
       return
$buf;

  
$ses_name = session_name();
   if (
strstr($url, "$session_name="))
       return
$buf;
  
  
$p = strpos($url, "#");
  
$ref = false;
   if(
$p){
      
$ref = substr($url, $p);
      
$url = substr($url, 0, $p);
   }
   if (
strlen($url)==0)
       return
$buf;
   if (!
strstr($url, "?"))
      
$url.="?";
   else
      
$url.="&amp;";
  
$url.=session_name() ."=".session_id();
   if(
$ref)
      
$url.=$ret;
   return
str_replace($url_orig, $url, $buf);
}
?>

It adds a field to urls and a fake form entry.

You can start the rewrite by doing the folowing at the start of the script:
<?php
function pa_set_trans_sid(){
   if (
defined('SID') ){ // use trans sid as its available
      
ini_set("session.use_cookies", "0");
      
ini_set("session.use_trans_sid", "true");
      
ini_set("url_rewriter.tags", "a=href,area=href,script=src,link=href,"
. "frame=src,input=src,form=fakeentry");
   }else{
      
ob_start('ob_sid_rewrite');
   }
}
?>
budfroggy a.t. adminmod d.o.t org
26-May-2005 08:21
For those of you run into sess_deleted files in your temp session directory, and have users complaining that they cannot log off, the cause is almost always due to the user's system time being off. Make sure that the user properly sets his or her time, date and time zone.

As a side note, if two users have system times set in the past, and both log onto a system, they will share the same sess_deleted file, which means that their identities could very well be swapped, leading to possible security breachs. I am going to look into code that might forcefully prevent this form happening.
Carlos Aya
18-May-2005 12:29
An bug of my own zoo that was hard to catch with sessions.

This may save time to someone else:

// in some page, after session_start
$_SESSION[$var] = $someValue;
// my bug: $var was wrong, as it didn't contain a valid PHP identifier.
$_SESSION['flag'] = 'here'; // flag is a valid PHP identifier... but...
// then redirect to another page with session_id and everything else ok

. . .
// in next page after session_start()
count($_SESSION) == 0
// ! yes, it's empty, as $var was wrong, that stoped the whole
// $_SESSION array to be stored

hope this saves time to others.
frank723 AT gmail DOT com
03-May-2005 04:27
Here is a script a made to initialize global variables when both GET and SESSION variables are defined. This is common when SESSION variables retain information that is changed by a GET value. For example, when a user selects a style, the url is tagged with ?style=STYLETYPEONE, so $_SESSION['style'] should be set to the get. However, if no get is set then the session variable should remain what it was. If the session variable isnt set either, then it should be set to the default value of the variable.

Here is the code:

# a session helpful thing, start a session, with default session values
# if get for that var is set set the var to th get otherwise use session
session_start();
$ses_vars = array('var1'=>var1defaultvalue, # list of passed get vars
   'var2'=>var2defaultvalue,
   'var3'=>var3defaultvalue);
foreach ($ses_vars as $var=>$default) {
   if (!isset($_SESSION[$var])) $_SESSION[$var] = $default;
   if (!isset($_GET[$var])) ${$var} = $_SESSION[$var];
   else ${$var} = $_GET[$var];
}

-Frank
http://entelekheia.net/
origami HAT cats.ucsc.edu
04-Apr-2005 12:57
Providing the enctype attribute of text/plain in a form tag causes the form submission to result in the _POST scope not being defined.
webmaster at paginadespud dot com
28-Mar-2005 07:10
hi all,
i've been troubles with sessions at my production server for weeks and today i've noticed the problem.

If you use /tmp as php sessions file dir, on a procuction server, system garbage will delete randomly files when a certain number os files are stored at tmp, so some sessions are deleted within 1 seconds, like my case.

Solution? use another dir for php sessions file, and be careful of using a shell script for your own garbage collection, called from cron, with this line:
cd /path/to/sessions; find -cmin +24 | xargs rm

Spud.
anders
02-Mar-2005 03:15
It's true that session variables are stored on-server, but for the server to know which session the user is using, a cookie is used. If you check your cookie cache, you'd see that the only session-related information you find in your cookie is a session id, no matter how much information you store in $_SESSION.
mat3582 at NOSPAM dot hotmail dot com
28-Feb-2005 11:36
Outputting a pdf file to a MSIE browser didn't work (MSIE mistook the file for an Active-X control,
then failed to download) untill I added
<?php
ini_set
('session.cache_limiter',"0");
?>
to my script. I hope this will help someone else.
trev at beammeupnowplease dot com
03-Jan-2005 05:09
You can't turn off session.use_trans_sid on an individual script basis until PHP5.

However, if you use ini_set('url_rewriter.tags', ''); at the top of your script this will stop the SID being written to the URL's in PHP4.

Hopefully will save someone else a frustrating couple of hours.

Trev
jphansen at uga dot edu
23-Dec-2004 04:23
If you assign a session subscript/key to the same name as a variable, the session variable will be volatile and lost upon navigating.

For example, if passing a setting that you want in $_SESSION, don't do this:

<?
$setting
= $_REQUEST['setting'];
if (!empty(
$setting))
  
$_SESSION['setting'] = $setting;
?>

Instead, rename $setting or $_SESSION['setting'].
Xenon_54
19-Dec-2004 07:27
The session support does not use the IP address for validation. It is based on cookies and URL rewriting.

The reason you lose your session when closing your browser and reconnecting to your ISP (so you are changing your IP), is that sessions are only valides for the visit on your web site, not more.

Changing your IP address will not affect your session except if you close your browser.
Michael Wells
22-Nov-2004 06:04
If you are trying to share sessions across a cluster of servers, and don't want to use NFS, or a relatively heavy and slow RDBMS, there is an excellent tool called ShareDance that can do it over a simple TCP protocol. ShareDance comes complete with a PHP interface example and works 'out of the box' for me.

http://sharedance.pureftpd.org/

My thanks to Frank Denis for writing this elegant, valuable piece of software.
Audun Rundberg
14-Nov-2004 05:50
If you're using header('Location:' . $url) to redirect the user to another page, you should use session_write_close() to save session data before the redirect. $_SESSION is normally serialized and written to the harddrive when the script ends.

Example:

<?php

$_SESSION
["Message"] = "The task was completed.";
session_write_close();
header('Location:' . $_SERVER["PHP_SELF"]);

?>

Without session_write_close(), this next piece of code would not output "The task was completed". (Assuming that this code is in place where the user was redirected.)

<?php

echo $_SESSION["Message"];

?>
irm at in3activa dot com
13-Sep-2004 08:57
Warnings :
session.bug_compat_42 and bug_compat_warn

Warnings may appears even if your code is correct,
because some asumptions of the developpers.

In practice, these warnings are automatic when your code results in something like:

$_SESSION['var']= NULL;

That is, the code assume that the programmer tried
to assign a unavailable (=NULL) variable because
register_globals is off.

Solution: assign anything but NULL. For example:

$_SESSION['var']= is_null($var) ? 0 : $var;
cryogen AT mac dot com
10-Sep-2004 02:02
Although this IS mentioned in the PHP manual, it is not very clear and can lead to some very hard to track down bugs.

When REGISTER_GLOBALS is ON on a server, local variables of the same name as a session variable can leak their values into the session during a POST or GET.

For example, if you run script "SESS_TEST1.PHP" below, the local var $animal will bleed its value of "I am an Elephant" into the session variable $_SESSION['animal'], which should have a value of "I am a Monkey".  Beware!

<?php
// SESS_TEST1.PHP
session_start();
$_SESSION['animal'] = 'I am a Monkey';
$animal = 'I am an Elephant';
$value = 249;

echo
"<script>window.location=\"sess_test2.php".
 
"?animal=$animal&value=$value\"</script>";
?>

<?php
// SESS_TEST2.PHP
session_start();
$animal = $_REQUEST['animal'];
$value  = $_REQUEST['value'];

echo
"SESSION['animal'] = ".$_SESSION['animal']." (should say \"I am a Monkey\")<br/>";
echo
"\$animal = ".$animal."<br/>";
echo
"\$value = ".$value."<br/>";
?>
Dopey
03-Sep-2004 08:06
Be careful when using the Content-Length header with session.use_trans_sid enabled. Technically, it might not be a bug, but PHP does not update the header when it adds the session ID to links in a page. The result is that only partial content is shown in a browser.

In short: if you use ob_get_length to figure out Content-Length, turn session.use_trans_sid off!
root[noSPAM]cyberdark.net
17-Aug-2004 05:55
A common problem with session.auto_start, when activated in php.ini file, is the fact that if you've php objects inside the session classes must be loaded before session in started. You'll run into trouble then...

To avoid this, if you cannot ask your sysadmin to modify the php.ini file, add this line to your .htaccess wherever you need it in your application (usually on top of your app):

php_value session.auto_start 0
bcage at tecdigital dot net
23-Jun-2004 10:24
[Quote]
Someone posted a message here saying you should just all use the MM shared memory management for sessions.  I'd like to CAUTION EVERYONE against using it!
 
I run a few webservers for a webhosting company, and we quickly ran in to PHP pages segfaulting Apache for unknown reasons, until we did a test with sessions.  It turns out that the sessions, while using the mm stuff, couldn't keep the data right.  I guess it was to do with the file locking issue mentioned in the documentation here (I didn't notice this until now!).
 
 Anyways, if you run a Unix machine that can map virtual memory to a mount point (like tmpfs or shm or whatever it may be called), use this instead.  It's volatile like mm, but works.  Only thing you don't get is hidden session info so that other people don't know how to open it easily - but it's better than trying to use mm and having the webserver crash all the time!

[EndQuote]

You're totally right, in my server (FreeBSD 5.2) when using mm to handle sessions, dotProject wouldn't even start, it crashed when accessing index.php. This was solved by creating a swap-backed memory disk with the following options

rw,-s60000,,-b=4096,-f=512,-i=560,-c=3,-m=0,nosuid,nodev,nosymfollow
schulze at telstra dot com dot not dot this dot bit
06-Jun-2004 01:10
sessions not sticking and cookies not setting with IE? took me ages to find the problem.

you need a 'compact privacy policy'! it's not hard once you know how!

this was too much for me: http://www.w3.org/TR/P3P/

but http://www.sitepoint.com/article/p3p-cookies-ie6/2 is very easy to apply

and a visit to this site is very worthwhile: http://www.privacycouncil.com/freep3pfix.php

happy PHP to all!

Erich
Osmos
09-May-2004 03:13
Note to the massage from "setec at freemail dot it" (01-Mar-2004 01:41).

For more flexibility I suggest replacing the string

<?php
_safe_set
($parse_url["scheme"], "http");
?>

with the following one:

<?php
_safe_set
($parse_url["scheme"], $_SERVER["HTTPS"] ? "https" : "http");
?>
Afternoon
04-May-2004 09:28
I found a good solution to create a persistent session by storing a persistence flag, ironically, in the session itelf. I start the session (which sends a Set-Cookie with no expiry time), read the flag and then, if the user wants a persistent session, stop and restart the session with the expiry time set using session_set_cookie_params, which then sends a cookie with a good expiry time. This solution has been quickly tested with all major browsers and seems to work.

I have outlined the whole process in my blog: http://aftnn.org/journal/508
Rikahs Design
14-Apr-2004 09:10
When setting url_rewriter.tags parameter in php.ini, make sure that you put quotes around the string portion like this:

url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"

or the PHP won't know what tags to insert the session id into.  My web host has a relatively current version of PHP and they still didn't have this parameter configured by default.
setec at freemail dot it
01-Mar-2004 10:41
This is a usefull code I have done that allows to make a redirection using headers with full support for sessions and HTTP 1.1.

<?php
  
function session_redirect ($url = "")
   {
       function
_safe_set (&$var_true, $var_false = "")
       {
           if (!isset (
$var_true))
           {
$var_true = $var_false; }
       }

      
$parse_url = parse_url ($url);
      
_safe_set ($parse_url["scheme"], "http");
      
_safe_set ($parse_url["host"], $_SERVER['HTTP_HOST']);
      
_safe_set ($parse_url["path"], "");
      
_safe_set ($parse_url["query"], "");
      
_safe_set ($parse_url["fragment"], "");
      
       if (
substr ($parse_url["path"], 0, 1) != "/")
       {
          
$parse_url["path"] = dirname ($_SERVER['PHP_SELF']) .
                          
"/" . $parse_url["path"];
       }
      
       if (
$parse_url["query"] != "")
       {
$parse_url["query"] = $parse_url["query"] . "&amp;"; }
      
$parse_url["query"] = "?" . $parse_url["query"] .
                        
session_name () . "=" .
                      
strip_tags (session_id ());
      
       if (
$parse_url["fragment"] != "")
       {
$parse_url["fragment"] = "#" . $parse_url["fragment"]; }
      
      
$url = $parse_url["scheme"] . "://" . $parse_url["host"] .
            
$parse_url["path"] . $parse_url["query"] .
            
$parse_url["fragment"];
      
      
session_write_close ();
      
header ("Location: " . $url);
       exit;     
   }
?>
gzink at zinkconsulting dot com
03-Dec-2003 11:57
[Editors note: I've just benchmarked this, and over a 100 element array the results are as follows: (average over 10 runs)

Standard Array: 0.102ms
$_SESSION: 0.197

This is in the extremely unlikely case of having to loop through 100 elements in a session variable. Remember, if you have that many elements in your session, something is wrong.]

A small warning! $_SESSION can be slooowwwww....

I've never heard of this, but it turns out $_SESSION is much slower than any regular array, even an exact copy of $_SESSION. Copying large amounts of data in/out of $_SESSION is seriously slow and each access to $_SESSION is noticeably slower than regular arrays.

The lesson I learned? Don't use $_SESSION in loops that run very much. Even copying data from $_SESSION before the loop won't help a lot if there's a lot of data there due to a delay that can be pretty hefty, almost equal to working directly on $_SESSION with foreach() and actually slower than working directly on $_SESSION if you need to put the data back in the array in my experience. It's better to pass the data another way if possible, i.e. save the SQL query and re-run, store in a database, etc.

Just a warning for those who may be using this array in medium to large loops or trying to pass lots of data. I hope it saves you the hours of optimizing I've had to spend!

-Galen
http://www.zinkconsulting.com/
pautzomat at web dot de
19-Nov-2003 09:05
Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID.

Of course, it says so in the documentation ('Passing the Session Id') and of course it makes perfectly sense to have that restriction, but here's what happened to me:
I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this:

$sHomeDirectory = 'http://my.server.com/one/of/my/projects'

which was used to make sure that all automatically generated links had the right prefix (just like $cfg['PmaAbsoluteUri'] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn't a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there...)

Skipping the 'http:' did the job.

OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours... Just don't do it ;)
orion at dr-alliance dot com
09-Aug-2003 12:52
Session ID's wont be carried over through meta refreshes, so make sure you add the variables (in GET format) to the URL.
IE )
<meta http-equiv=\"refresh\" content=\"1;URL=index.php?PHPSESSID=$PHPSESSID\">
tim at digicol dot de
04-Feb-2003 07:14
Be careful when using ini_set to change the  session.gc_maxlifetime value locally for your script:

You will trash other people's sessions when garbage collection takes place (and they will trash yours) regardless of their (your) intended session.gc_maxlifetime, because the session_name is not taken into account during garbage collection.

Create an own directory and set session.save_path to it, so that your session files don't get mixed.
jmgonzal_NOSPAM_at_NOESPAM_netred_DOT_cl
13-Oct-2002 12:43
If you have problem to download a file from your PHP , and you have IE (any version) and apache for server with SSL, check the reference of: session-cache-limiter

My best solution is change the php.ini from

session.cache_limiter = nocache

to:

session.cache_limiter = private, must-revalidate
twocandles3000@hotmail
14-May-2002 08:34
Storing class instances in session.

As long as a class MUST be declared BEFORE the session starts and unserializes the session info, i'm using this approach.

0: Set in php.ini session.auto_start = 0
1: create myclass.inc where the class is declared.
2: put in another file, say header.inc, this lines of code:
include_once( "myclass.inc" );
session_start();
3: set in php.ini the auto_prepend_file= "path_to_my_file/header.inc"

Following this steps, the session is started at every page and myclass is always available, avoiding to write the session_start() function at every page.
stoiev at ig dot com
20-Mar-2002 06:10
Carefull when you are working in PHP with WML. The arg separator used to put de PHPSESSID variable in URL is '&' by default, and this cause a Compile Error in browsers:

<anchor><go href="index.php?estate=1&PHPSESSID=12345678abcde"></go>

instead of this:

<anchor><go href="index.php?estate=1&#38;PHPSESSID=12345678abcde"></go>

It?s safety include the line:
ini_set ( "arg_separator", "&#38;");

to change the arg separator, it worked in PHP 4.1.2

Another thing that the onpick tag is not defined in the url_rewriter.tags list by default(if there are others, i don?t now). This is must be added in php.ini file.

* In most case the WAP GateWay accepts cookies an the auto-transpass-SID is not necessary, it?s hard to find problems with this.
ricmarques at spamcop dot net
16-Oct-2000 02:16
Regarding session.cache_limiter :

For those of you who - like me - had trouble finding the meaning of the possible values (nocache, public and private), here's the explaination taken from the HTTP 1.1 Specification at
http://www.w3.org/Protocols/rfc2068/rfc2068


"14.9.1 What is Cachable

[snip]

public
  Indicates that the response is cachable by any cache, even if it would normally be non-cachable or cachable only within a non-shared cache. (See also Authorization, section 14.8, for additional details.)

private
  Indicates that all or part of the response message is intended for a  single user and MUST NOT be cached by a shared cache. This allows an origin server to state that the specified parts of the response are intended for only one user and are not a valid response for requests by other users. A private (non-shared) cache may cache the response.

  Note: This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

no-cache
  Indicates that all or part of the response message MUST NOT be cached anywhere. This allows an origin server to prevent caching even by caches that have been configured to return stale responses to client requests.

  Note: Most HTTP/1.0 caches will not recognize or obey this directive."
shanemayer42 at yahoo dot com
20-Aug-2000 04:11
Session Garbage Collection Observation:

It appears that session file garbage collection occurs AFTER the current session is loaded. 

This means that:
even if session.gc_maxlifetime = 1 second,
if someone starts a session A and no one starts a session for an hour,  that person can reconnect to session A and all of their previous session values will be available (That is, session A will not be cleaned up even though it is older than gc_maxlifetime).

<session_pgsql_status session_cache_expire>
  Last updated: Wed, 26 Oct 2005
show source | credits | stats | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2006 The PHP Group
All rights reserved.
This mirror generously provided by: Tomato Interactive
Last updated: Fri Feb 24 12:12:08 2006 CET