PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previoussesam_settransactionsession_cache_expirenext
Last updated: Tue, 11 Jun 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Czech | Dutch | Finnish | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

XCI. Sessions

La gestion des sessions avec PHP est un moyen de sauver des informations entre deux acc�s. Cela permet notamment de construire des applications personnalis�es, et d'accro�tre l'attrait de votre site.

Si vous connaissez d�j� la gestion des sessions avec phplib, vous remarquerez que certains concepts sont similaires.

Chaque visiteur qui acc�de � votre site se voit assigner un num�ro d'identifiant, appel� plus loin "identifiant de session". Celui-ci est enregistr� soit dans un cookie, chez le client, soit dans l'URL.

Les sessions vous permettront d'enregistrer des variables pour les pr�server et les r�utiliser tout au long de la visites de votre site. Lorsqu'un visiteur acc�dere � votre site, PHP v�rifiera automatiquement (si session.auto_start est � 1) ou manuellement (explicitement avec session_start() ou implicitement avec session_register()) si une session a d�j� �t� ouverte. Si une telle session existe d�j�, l'environnement pr�c�dent sera recr��.

Toutes les variables � enregistrer seront enregistr�es sur le disque � la fin de chaque requ�te. Les variables enregistr�es mais non d�finies seront marqu�es comme telles. Lors des acc�s ult�rieurs, elles ne seront d�finies que si l'utilisateur le fait.

Les options track_vars et gpc_globals modifient la fa�on dont les variables sont recharg�es.

Note�: Depuis PHP 4.0.3, track_vars est toujours activ�e.

Si track_vars est activ�e, et register_globals d�sactiv�e, alors les variables de session seront accessibles uniquement dans le tableau associatif global $HTTP_STATE_VARS. Les variables de session lues seront disponibles dans $HTTP_STATE_VARS.

Exemple 1. Enregistrer une variable lorsque l'option track_vars est activ�e

<?php
  session_register("compte");
  $HTTP_SESSION_VARS["compte"]++;
?>

Si register_globals est activ�e, alors les variables de session seront plac�es dans les variables globales associ�es.

Exemple 2. Enregistrer une variable lorsque register_globals est activ�e

<?php
  session_register("compte");
  $compte++;
?>

Si les deux options track_vars et register_globals sont activ�es, alors les variables globales et $HTTP_STATE_VARS contiendront les valeurs de session.

Il y a deux modes de propagation de l'identifiant de session :

  • Cookies

  • Param�tre URL

Le module de session supporte les deux techniques. La m�thode par cookies est optimale, mais �tant donn� son peu de fiabilit� (les clients peuvent refuser ou effacer les cookies), on ne peut pas se contenter de cette technique. La deuxi�me m�thode place l'identifiant de session directement dans l'URL.

PHP est capable de g�rer ceci de mani�re transparente, lorsque vous le compilez avec l'option --enable-trans-sid. Dans ce cas, les URL relatives seront modifi�es pour contenir l'identifiant de session automatiquement. Sinon, vous pouvez toujours utiliser la constante SID, qui sera d�finie si le client n'envoie pas le cookie appropri�. SID prend la forme de session_name=session_id, ou bien, c'est une cha�ne vide.

Note�: La fonction qui g�rera l'�criture des donn�es ne sera appel�e qu'une fois que le script aura envoy� toutes ses donn�es. Ainsi, les affichages tent�s par cette fonction ne pourront jamais �tre re�us par le navigateur. Si un tel affichage est n�cessaire, il est conseill� d'�crire les debugs dans un fichier.

L'exemple suivant montre comment enregistrer une variable, et comment relier correctement des pages avec SID.

Exemple 3. Compter le nombre de hits d'un utilisateur.

<?php
  session_register("compteur");
  $compteur++;
?>
Salut visiteur, vous avez vu cette page <?php echo $compteur; ?> times.<P>
<php?
# le <?=SID> est n�cessaire pour transmettre l'identifiant de session
# au cas o� les utilisateurs auraient inactiv� les cookies
?>

Pour continuer, <A HREF="nextpage.php?<?=SID"?>clique ici</?>

Le <?=SID-> n'est pas n�cessaire, si l'option --enable-trans-sid a �t� utilis�e pour compiler PHP.

Note�: Les URL absolues sont consid�r�es comme des sites externes, et PHP ne leur attribuera pas le SID, qui pourrait repr�senter un trou de s�curit�.

Pour enregistrer ces informations dans une base de donn�es, il vous faut utiliser la fonction session_set_save_handler(). Il faudra alors impl�menter la fonction suivante pour l'adapter � MySQL ou � toute autre base de donn�es :

Le syst�me de gestion des sessions dispose d'un grand nombre d'options, qui sont plac�es dans le fichier php.ini. En voici un survol rapide :

  • session.save_handler d�finit les noms des fonctions qui seront utilis�es pour enregistrer et retrouver les donn�es associ�es � une session. Par d�faut, les sessions sont enregistr�es dans des fichiers.

  • session.save_path d�finit l'argument qui est pass� � la fonction de sauvegarde. Si vous utilisez la sauvegarde par fichier, cet argument est le chemin jusqu'au dossier o� les fichiers sont cr��s. Par d�faut, le dossier est /tmp.

    Avertissement

    Si le dossier que vous utilisez a les droits de lecture universels, comme /tmp (valeur par d�faut), les autres utilisateurs du serveur peuvent aussi lire ces fichiers, et s'immiscer dans vos sessions.

  • session.name sp�cifie le nom de la session, qui sera utilis� comme nom de cookie. Par d�faut : PHPSESSID.

  • session.auto_start indique qu'une session doit commencer automatiquement lors de la premier requ�te. Par d�faut, la valeur est � 0 (inactiv�).

  • session.lifetime fixe la dur�e de vie, en secondes, du cookie envoy� au client. La valeur 0 signifie "jusqu'� ce que le client soit ferm�". Par d�faut � 0 (inactiv�).

  • session.serialize_handler d�finit le nom de la fonction qui sera utilis�e pour enregistrer et relire les donn�s. Actuellement, c'est un format interne de PHP (nom : php) et WDDX (nom : wddx). WDDX n'est utilisable que si PHP a �t� compil� avec le support WDDX. Par d�faut, c'est le mode php qui est s�lectionn�.

  • session.gc_probability pr�cise la probabilit� que la routine gc (garbage collection) soit lanc�e, en pourcentage. Par d�faut, la valeur est � 1.

  • session.gc_maxlifetime fixe la dur�e, en secondes, au-del� de laquelle les donn�es consid�r�es comme inutiles seront supprim�es.

  • session.referer_check repr�sente la sous-cha�ne que vous utilisez pour v�rifier la provenance de l'internaute. Si l'ent�te HTTP Referer vous est fournie par le navigateur et que cette sous-cha�ne n'est pas trouv�e, la session qui vous est fournie sera consid�r�e comme invalide (car provenant probablement d'un autre site que le votre). Par d�faut, cette cha�ne est vide.

  • session.entropy_file est le chemin jusqu'� une source externe (fichier) d'entropie, qui sera utilis�e lors de la cr�ation de l'identifiant de session. Par exemple, /dev/random ou /dev/urandom qui sont disponibles sur de nombreux syst�mes UNIX.

  • session.entropy_length pr�cise le nombre d'octets qui seront lus dans le fichier ci-dessus. Par d�faut, 0 (inactiv�).

  • session.use_cookies cookies indique si le module doit utiliser des cookies pour enregistrer l'identifiant de session chez le client. Par d�faut, 1 (activ�).

  • session.cookie_path sp�cifie le chemin � utiliser avec session_cookie. Par d�faut, /.

  • session.cookie_domain sp�cifie le domaine � utiliser avec session_cookie. Par d�faut, rien du tout.

  • session.cache_limiter sp�cifie le contr�le du cache, � utiliser avec les pages de session (nocache/private/public). Par d�faut, nocache.

  • session.cache_expire sp�cifie la dur�e de vie des pages de session cach�es, en minutes, mais sans que cela ait d'effets sur le limiteur "nocache". Par d�faut, 180.

  • session.use_trans_sid indique si le support du SID est activ� ou pas, lors de la compilation avec l'option --enable-trans-sid. Par d�faut, elle vaut 1 (activ�e).

  • url_rewriter.tags spefifies which html tags are rewritten to include session id if transient sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form=fakeentry

Note�: La gestion des sessions a �t� ajout�e en PHP 4.0.

Table des mati�res
session_cache_expire -- Return current cache expire
session_cache_limiter -- Lit et/ou modifie le limiteur de cache
session_decode --  D�code les donn�es de session � partir d'une cha�ne
session_destroy --  D�truit toutes les donn�es enregistr�es d'une session
session_encode --  Encode les donn�es de session dans une cha�ne
session_get_cookie_params --  Lit les param�tres du cookie de session
session_id -- Affecte et/ou retourne l'identifiant de session courante
session_is_registered --  Indique si une variable a �t� enregistr�e dans la session ou pas
session_module_name -- Affecte et/ou retourne le module courant de session courante
session_name -- Affecte et/ou retourne le nom de la session courante
session_readonly -- Lit les variables de session sans verrouiller les donn�es
session_register --  Enregistre une variable dans la session courante
session_save_path -- Affecte et/ou retourne le chemin de sauvegarde de la session courante
session_set_cookie_params --  Modifie les param�tres du cookie de session
session_set_save_handler --  D�finit les fonctions utilisateurs de stockage des sessions
session_start -- Initialise les donn�es de session
session_unregister --  Supprime une variable dans la session courante
session_unset --  D�truit toutes les variables de session
session_write_close -- Write session data and end session
User Contributed Notes
Sessions
add a note about notes

18-Feb-2000 11:40

When using Header("Location: url"), you must add a
"?".sid to the end or your session will not carry to the next
page. i.e. Header("Location: url?".sid)  :(


30-Jun-2000 03:29

1) If you're writing your own handler, make sure session.save_handler =
user is in your PHP config. 4.0.1 (fixed in 4.0.2) will crap out with an
error when it tries to write the data back to the session store at the end
of your page's processing.

2) If you want a session handler for mysql: 


08-Aug-2000 10:09

The description of the session.referer_check setting is incorrect: it is
not a boolean, but a string. If it is not empty and a none empty Referer
has been given by the browser, PHP does a substring search of the
referer_check value in the Referer. If the check value is present in the
Referer, PHP creates a new session instead of using the existing one.
The default value of referer_check is the empty string (meaning no checking should be done).
(Tested with PHP4.0.1pl2)


13-Aug-2000 01:27

One clarification to what [email protected] wrote on 12-Mar-2000:
 
When putting objects in a session, you need to have declared the class of
your session managed objects BEFORE they are restored with a
session_register or equivalent call. 

That means before the session_start()!


20-Aug-2000 01: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).


30-Aug-2000 04:25

> This means that a user can takeover the session of another user if he
> knows (or guesses) the other user's session id. (all web applications
are
> vulnerable to this attack).

While it is true that you can take over other users' session ID's, there
are
several things you can do to prevent this from happening.
One way is to store the remote user's IP address on the server.

When you start a new session, do this:
$ipaddr = $REMOTE_ADDR;
session_register("ipaddr");

And when the user requests a document with sensitive data
verify his/her IP address:
if($ipaddr != $REMOTE_ADDR) {
  echo "Go away!\n";
  exit;
}

[email protected]:

WARNING: this does not work if the user
lives behind a proxy-farm as remote
address will change if different requests
are servered by different hosts in the 
proxy pool

andreyhristov at yahoo.com
12-Sep-2000 08:19

In reply to  [email protected]:
When you use REMOTE_ADDR for getting the IP of the current user, 

sometimes you get  the IP of the ISP Cache server.  
When this happens, the HTTP_X_FORWARDED_FOR is also set, it 
contains the IP of the user. 
So with this script, you always get the right IP: 

<PRE>

if (getenv(HTTP_X_FORWARDED_FOR)){ 

$ip=getenv(HTTP_X_FORWARDED_FOR); 

} 

else { 

$ip=getenv(REMOTE_ADDR); 

} 

</PRE>
And also:
Note that the X-Forwarded for header might contain multiple addresses,
comma separated, if the request was forwarded through multiple proxies.

Finally, note that any user can add an X-Forwarded-For header themselves.
The header is only good for traceback information, never for
authentication. If you use it for traceback, just log the entire
X-Forwarded-For header, along with the REMOTE_ADDR.
This text is written by :
[email protected] (before "And also:" and
[email protected] all other.

--
Editor's Note: We cannot trust HTTP_X_FORWARDED_FOR.


15-Oct-2000 11: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



"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."


11-Dec-2000 12:32

This might be useful to those strugling with ini settings like
cache_limiter. 

To view the ini settings, you can use
 ini_get("session.cache_limiter")
And to change
 ini_set("session.cache_limiter","public");

--
Editor's Note: session_cache_limiter() function does the same.


15-Dec-2000 10:58

Note. Going to  and  will create two
_seperate_ sessions. If you use sessions, you should make sure that the
user sticks with one base url, and doesnt switch between them.

I had lot of problems with this, since IE (somehow) handled it, but
Netscape didn't.


16-Dec-2000 01:41

A database driven PHP4 session handler that supports MySQL, PostgreSQL,
Oracle, MSSQL, Interbase, Access, FoxPro, Sybase, ODBC and ADO is
available at 

  

This uses the ADODB database wrapper library.


28-Dec-2000 02:49

To get more secure session IDs, here is what I use on GNU/linux :

ini_alter("session.cookie_lifetime", "86400");
ini_alter("session.entropy_file","/dev/urandom");
ini_alter("session.entropy_length", "512");

You can also use /dev/random instead of /dev/urandom but it's a slower.


12-Jan-2001 07:27

It seems that objects are not stored recursively in sessions.   For
example, we have an object variable $HUB registered and stored in the
session, it has a field $config, but it looks like $HUB->$config
doesn't get stored with $HUB.  (although all the non-object fields get
stored fine)

There doesn't seem to be any documentation about this.


31-Jan-2001 03:19

It seems that session_unregister(name) unsets all variables with the same
name,
e.g. this code will kill variable "login", that you might have
got from an HTTP form and that you're  going to use in your script
 session_start();
 session_unregister("login");
....
 echo $login; // You'll see nothing

I had to add 

 reset ($HTTP_POST_VARS);
 while (list ($key, $val) = each ($HTTP_POST_VARS)) {
    $$key = $val;
 } 
to set back the variables I have got from form.

--
Editor's Note: session_unregister() does not care if value is session
variable or not. i.e. it unregister the variable from session and unset
the variable.


24-Feb-2001 12:06

-->session objects part II:
I got this to work, if you are also having problems with sessions with
register_globals turned off and none of the other suggestions work, you
may as well give it a try:

class session_variables{var $count=0;}
session_start();
if (isset($HTTP_SESSION_VARS["z"]))
  $z=&$HTTP_SESSION_VARS["z"];
else {
  $z=new session_variables();
  $HTTP_SESSION_VARS["z"]=&$z;
}
print $z->count++;

--
Editor's note: Original code uses session_is_registered(). DO NOT USE
session_register(), session_is_registered() and session_unregister(), if
you are using $HTTP_SESSION_VARS/$_SESSION.


27-Feb-2001 04:21

[Editor's note: see serialize() for more info on the format referred in
this note]

Two quick things...
First off: it appears for some reason even with use_cookies = 0; NS's session files stored on my server have a size of 0bytes. Whereas all other browsers tried this problem did not arise and the session files contained the appropriate values.
Secondly whilst investigating all of this I learned some interesting things about how the session files stored sessions. Small slice of part of a session file: b|s:2:"ie";lang|s:2:"en";!resw|!resh| Set variables are delimited by ";" in format of: varname|s:number:"value"; I have not yet found out what s:number is. Registerd vars that contain no value are !varname which makes sense. Hope this was of help to someone, and to anyone else with the first mentioned issue your perhaps not the only one. G.D.

02-Mar-2001 07:52
Correction to above: Must call session_register("z") and then
initialize $HTTP_SESSION_VARS["z"] to make class persist across
different pages.
//---------------------------------------------------
session_start(); 
if (session_is_registered("z"))
$z=&$HTTP_SESSION_VARS["z"]; 
else {
      $z=new session_variables();
      session_register("z"); //--necessary
      $HTTP_SESSION_VARS["z"]=&$z;
} 
//---------------------------------------------------


13-Mar-2001 04:15

How to fallback from COOKIE session to URL:

According to zend.com

==========
HTTP session handling, including fallback system management, is built into
PHP 4.0, thanks to its new library. 
==========

According to other descriptions at zend.com. PHP4 session can fallback
from cookie session to URL. If
- trans-sid is on 
- Relative URI is used

[I've not verified this by myself, yet. However, I thought PHP4 Session
will not fallback automatically until now. I think it worth describing it
explicitly here.]


03-May-2001 04:03

"You then spawn a new browser window (CTRL-N in IE) which keeps the
browser session ID the same, and type in the url for the script"

That means you know the session ID in which case of course you will have
access to the session data.  This is a known issue.  If you guess the
correct session ID, you can get access to that session's data.  Try doing
what you say but without spawning a new browser windows that knows the
session ID.


10-May-2001 10:14

To [email protected] 03-May-2001 10:03
The anonymous post from 22-Apr-2001 09:53 is not talking about session hijacking but a local exploit. Of course anyone can hijack a session by getting the sessionID from listening to network traffic or just physically sitting at your desktop.
The point is the following (I believe): A machine have users alice and oscar. Alice has an application in that uses sessions. Oscar can set up php scripts in his directory and if he guesses (or just looks at the cookie in he's own browser, or just goes to he's own page since the cookie will be sent there too) the sessionid of an ongoing session he (in he's scripts, not browser) will get access (read and write) to all of the session variables in alices application.
The solution that is missing is that there should be a way of restricting the scope of session variables to only certain directories.

A temporary fix would be to serialize and encrypt your variables and then store that as a sessionvar. But since files have to be readable to the webserver, this usually means oscar can read the source too. Right? So he'll be able to use the same encryption and password anyway.(Hmm... never thought of this, but this generalizes to reading all kinds of interesting stuff from other users php-scripts like business logic, how and with what password to connect to a database... Reading other peoples public_html when it just contained html just wasn't that exciting.)
Was this clear enough? Am I missing something? Didn't bother to test... henrik


15-May-2001 05:08

"Note: Non-relative URLs are assummed to point to external sites and
hence don't append the SID, as it would be a security risk to leak the SID
to an different server."

Doesn't the browser send it anyway as a referer?

postings.php.net at hans-spath.de
17-May-2001 11:41

When register_globals is turned on, changes in $HTTP_SESSION_VARS won't be
saved to session.

Because I wanted to use $HTTP_SESSION_VARS without turning
register_globals off, I wrote that "workaround" function below.
It should be called at the end of every PHP script that modifies
$HTTP_SESSION_VARS.

/* delete the dots before using ;) */
function session_regglobals_workaround() // by Hans Spath
{
. global $HTTP_SESSION_VARS;

. if ( ini_get('register_globals') )
. . foreach ( $HTTP_SESSION_VARS as $varname=>$value )
. . . if ( session_is_registered($varname) )
. . . . $GLOBALS[$varname] = $value;
}

comments? critics? <postings.php.net at hans-spath.de>


22-May-2001 05:42

I had a hair-raising problem with PHPSESSID parameters automatically added
to all URL strings.
I guess it has to do with the --enable-trans-sid compilation option.

[original message truncated]

[Editor's Note: Set the configuration directive session.use_trans_sid to 0
to disable this behavior.

  [email protected]]


29-May-2001 03:25

I thought for a bit (wrongly) that you'd have seprate session for each
subdirectory.
The trouble: when developing on localhost/127.0.0.1 and then reading a
directory listing. Apache changes the url to the actual hostname.  The
browser will not send the sessionid cookie to a "different"
host.


03-Jun-2001 06:53

If your using PHP session handling with PostgreSQL as session storage, a
efficient method of handling garbage collection would be a rule:

create rule rle_sessions_gc as on insert into sessions where (random()
>= 0.7) do delete from sessions where expiry <= current_timestamp;

this rule assumes that the sessions table has an expiry field into which
is placed the timestamp at which the session should expire; change the
value random is checked against to change the probability of garbage
collection.

paul at cnt dot org
15-Jun-2001 05:52

It appears as though, despite trans-sid and the URL rewriting the session
handling does, if you do a HTTP-type redirect, i.e. using

header("Location: some-url.php")

the session id is not passed along. So you have to manually rewrite it for those without cookies.


krypton
16-Jun-2001 04:48

For all users who get the error: "Headers already sent", you must
know that the session code must appear in the php page BEFORE anything is
print, so before the <HTML> tag.


19-Jun-2001 08:42

I just spent valuable 15 minutes wrestling with this. (PHP 4.0.5 here.)

It seems that if register_globals is on, it does not store the changes
that take place in the $HTTP_SESSION_VARS[] array.

For example, I had this code in one page:

session_register('mp3com');
$HTTP_SESSION_VARS['mp3com'] = 'mp3.com/ilp';  // junk value

Another page asked for the value of 'mp3com' session var, but the value
was not provided with the session data. 

As soon as I turned off register_globals in the configuration file,
$HTTP_SESSION_VARS began working as intended.

Apparently what happens is that with register_globals turned on, PHP does
mirror the incoming session variables upon session_start() in the
$HTTP_SESSION_VARS array. However, when saving the state of the session
variables, if register_globals are on, it ignores the $HTTP_SESSION_VARS
values for the registered session variables and instead takes them from
the global scope. Since I never put $mp3com into the global scope, PHP
probably thought that I "unset" $mp3com and did not save it.


28-Jun-2001 05:02

A quick note on a feature/security threat I discovered out of neccesity:
I am developing for i-mode, and for some reason when I use the POST method
with sessions, the session doesn't get sent. i-mode servers do some
parsing, and since the pages worked fine in IE, I thought about what to
do. First I put a hidden field in the form for SID, but for some reason
this didn't work either. I knew, despite some efforts on your part to hide
this fact from a user, that the session ID was actually passed in a
variable called PHPSESSID. I found this out by looking at the URL on my
i-mode handset, which displayed the entire URL, including this. Anyway, I
added the following line to my form:
print ' <input type=hidden name="PHPSESSID"
value="'.session_id().'">';
It works fine now, on both handset and IE. The problem as I see it is that
anyone could use the PHPSESSID variable to hijack someone's session. 
In fact, I tried appending it to a URL of a form, with a session value
from another session (one from a different IP), and it gave me their
username, their password, and the ability to input data into the form. It
wasn't difficult, and I am no hacker. I really want to use this feature,
but I actually need it for sample code I am writing for a book, and don't
want to expose a security threat. I guess adding a user's IP address to my
authentication would make it fairly secure. Hmm...


03-Jul-2001 01:18

The above states:

"There are two methods to propagate a session id:


Cookies

URL parameter


The session module supports both methods. Cookies are optimal, but since
they are not reliable (clients are not bound to accept them), we cannot
rely
on them. The second method embeds the session id directly into URLs.

PHP is capable of doing this transparently when compiled
with --enable-trans-sid. If you enable this option, relative URIs will be
changed to contain the session id automatically."


I can't seem to get this last part to work with cookies disabled.  Any
insight would be appreciated.


03-Jul-2001 04:30

I found the problem.  I had compiled PHP with '--enable-trans-sid'. 
However, I did not perform a 'make clean' before I did it, so the
configuration invocation did not "take".  I went back, did it
right, and now it works like a charm.


12-Jul-2001 02:19

It APPEARS that the implementation of sessions in entirely contingent upon
a single web-server being the destination?  Are there solutions for load
balanced servers and/or web servers where DNS-round robin is used to
cheaply load balance?  I can't envision how a session started on
www1.example.com would successfully apply to the next page served from
www2.example.com from an otherwise identical pair of webservers...  HELP?!


19-Jul-2001 04:59

As mentioned in the session documentation, when php is compiled with
--enable_trans_sid, the session id is automatically appened to URLs in a
HTML document (where a session is started).

This presents a problem when there is a link to a downloadable file;  the
session is is appended such that "download.exe" becomes
"download.exe?PHPSESSID=<session id>".  The only way I
could think of to get around this was to use
onClick="window.loctaion='download.exe'" as a href...


21-Jul-2001 04:25

Simple/Effective Session Handling lib for your (part of) website. 
Use near top of pages with e.g. 
include_once("session.php");	  loadMySession();

<?php

$SID = "";				// declare global

function constructSession() {
  session_start();
  $GLOBALS["SID"] = "PHPSESSID=".session_id();
  session_register("var1");   $GLOBALS["var1"] =
"var1_Default";
  ...
}
 
// not session_destroy() if independent sections on website
function destroyMySession() {
  session_start();    
  session_unregister("var1");
  ...
}
  
function loadMySession() {
  session_start();
  $GLOBALS["SID"] = "PHPSESSID=".session_id();
  $GLOBALS["var1"] = $HTTP_SESSION_VARS["var1"];    
// overwrites params from POST
  ...
}

// I couldn't write to $HTTP_SESSION_VARS[], so using $GLOBALS
function setSessionVar ($var, $val) {  $GLOBALS[$var] = $val; } 
function sessionVar ($var) {  return $GLOBALS[$var];  }

?>


25-Jul-2001 05:58

I've done some investigations on sessions and read comments by other
readers.  Here are some conclusions (based on PHP 4.0.4 p11):

- always call session_start() first as it sends headers for cookies.  You
need to do this even before calling session_destroy().
- check if a variable is registered using session_is_registered() before
using it.
- using session_id() to get the session id is more reliable than using the
$PHPSESSID variable.


31-Jul-2001 11:12

Small but i think helpfull comment:
Using session_name("xyz"); requires a session_name("xyz"); before EACH session_start();. Otherwise everytime you call the needed session_start(); in your script, a new session is defined and your registered vars are lost.
--xpo

06-Aug-2001 04:40
<?
#############################################
# REFERENCE JUGGLING WITH HTTP_SESSION_VARS 
#   needed for session vars when            
#   register_globals is off                 
#############################################
function & sess_reg($x){
global $HTTP_SESSION_VARS;
   session_register( & $HTTP_SESSION_VARS[$x]);
   return $HTTP_SESSION_VARS[$x];
}  

//session_start();
$foo = & sess_reg("foo");

//main program
echo $foo++;

var_dump($HTTP_SESSION_VARS);
#############################################


07-Aug-2001 06:13

Hay dos formas de propagar un id de sesion: mediante cookies o mediante
par�metros URL. Pues bien, seg�n la documentaci�n PHP es capaz de hacer
esto de forma transparente (si enable-trans-id = 1).

El problema est� en que si se llama una URL desde Javascript, el id de
sesion no se propaga automaticamente.


09-Aug-2001 11:18

[Editors note:
Netscape obviously doesn't accept your gz'ed page, so PHP sends it in
normal format, and then SID can do its job.

It doesn't work when the page is really gz'ed, as is (obviously) the case
with IE. (strange, IE better than NS? ;-)
 [email protected]]

Hi,

I read somewhere (PHP weekly summary iirc) that --enable-trans-sid only
works without output buffering enabled. I am making heavy use of output
buffering (via the global ob_gzhandler), but funnily enough, transparent
SIDs *do* work when I access the site with Netscape 4.7, but fail to work
with IE5.5. Any ideas what might be the cause of this behaviour?

Holger


10-Aug-2001 04:07

Re: Remember that you CANNOT override a EXISTING session variable with a
FORM(post)



Here is a simple work-around, if you for some reason want to override
session variables with POST variables :


session_register(...some variables...);

foreach($HTTP_POST_VARS as $key=>$value){

  $$key=$value;

}


22-Aug-2001 05:13

I was trying to keep track of some pretty detailed statistics of a website

(mostly client side) and also run server side sessions to hold database
information.
I kept getting "header already sent...." errors and my session
variables weren't 
staying registered - a total mess. I was using cookies to track statistics
about a given user of 
the website. I finally figured out a nice way to use both client and
server side 
variables and keep them constant across multiple pages. Here is how it's
done.

First: Client side tracking.

Many sites keep track of who hits them, and they usually do this by
sending the client a cookie 
with some registered id that might correspond to a id system at the
database level. In the
following example I used a cookie id that is used to locate information in
a mysql database.

So, prepend something like this to the main index page of your site - I've
left statistic information
out to make things brief.

<?php
	if(isset($statsid)) //Check to see if the stats cookie has been sent.
		// Update the database information. This can include host and page
information.
	else {
		$newid = random_string(); // Calculate a new statistics id number or
whatever you want. 
		// Create a new stats database entry with the new id.
		setcookie("statsid",$newid);
                session_id($newid); // Server side php session id.
		session_start();
		session_register("statsid"); // Register the id variable - now
both client and server.
	     }  
?>

The perpuse of registering that statsid in that last step is so your index
page can 
use that session for other variables without screwing up the stats
logging. Email me
if you want detailed information about logging activity. 

The next step is creating a script that with log link activity so you can
know what pages are visited.
Again, this is only a short (stripped) example but it should be enough to
get the idea across. Use something
like the following script as the target of all <a
href="track.php"> tags.

// track.php
<?php
	// First, at each link check to see if the browser has cookie support.
	// Here is an exmple of how this is done.
	$support = 0; 
        if (isset($check) && ($browser == "check"))
$support = 1; 
        if (!isset($CCHK)) { 
	   setcookie("browser", "check"); 
           header("Location: $PHP_SELF?CCHK=1"); }

	// Parse the query sent to the track script so that we can redirect
correctly.
	// Example: $query = "some var passed to track.php";

	if(isset($statsid)) {
		// Make the necessary database updates based on $statsid.
		// Pull whatever environment variables and info you want.
		setcookie("statsid",$statsid); } 
		// We set the statsid cookie here because browsers associate client side

		// variable with where they cam from.
	else {  // Same as above.
		$newid = random_string(); // Calculate a new statistics id number or
whatever you want. 
		// Create a new stats database entry with the new id.
		setcookie("statsid",$newid);
                session_id($newid); // Server side php session id.
		session_start();
		session_register("statsid"); // Register the id variable - now
both client and server.
		// Remember that we only init this php session if there is no record of
the user in the db.
		// This way they are logged regardless of how they arrive at the site.
	     }
?> 

So now we have a stats logger that will keep track of what a browser of
your site does. 
Again, the problem I ran into is that prepending the first script and
useing track.php would interfer
with sessions I was trying to run at the the start of other pages on my
site. The solution is to use the cookie
information (if availiable) to hook into the same php session for all
pages on your site. 

Here is the code you want to prepend all other pages with.

<?php
	// Check for the cookie given by the stats setup.
	if (isset($statsid)) {
	   $sid = $statsid; // Set the session id variable with the id of the
stats system.
	else if ($passid) { $sid = $passid; } // If cookies aren't enabled by the
user, enable the possibility of
					      // passing id information. This is the hardass way to track
movement on
					      // your site regardless of what the user wants - :)
	else { $sid = random_string(); } // Or, just start a new session id for
this page.
	session_id($sid);
	session_start(); // Since the stats scripts keep track of what id the
user is associated with 
			 // this is also a really nice way to maintain consistency on your
site.
?>	


The nice thing about this  approach is that if the user has cookies turned
off the stats store only the initial 
connection to the website (i.e you still know how hits the site) and php
sessions are created randomly to fit
your needs. If cookies are enabled or you wish to track variables with URL
querys then the same php session 
(using the stats cookie id) can be maintained throughout the course of a
given user's visit. You may have run 
into the problem of trying to run multiple php sessions - a  mess. This
approach eliminates the problem.
Once the session is started on a given page you have access to all
registered variables on the site. And the stats
system works right along side with no complaints.

Email me if you want detailed information on how to implement this. I used
this method on my site and I
use sessions heavily on many pages to store db info. Enjoy.

Nolan Goodnight

bester at tamix dot com
09-Sep-2001 11:35

Instead of just using a session ID to validate the user, try storing a
session variable containing the user's password as well (Using MD5
encryption, of course :) ). Then, write yourself a simple (seperate)
script that you can use to validate the user, and which you can include (
include("./thisfile.php"); ) in your scripts.


23-Sep-2001 04:23

Is it possible to create a script that counts how many users are currently
on a page. I was thinking about writing something that counts the number
of sessions currently registered or something. Any thoughts??


23-Sep-2001 10:43

I just wanted to point out that on one server I lost session variables,
when I refered to a script file only with code/, but code/index.php worked
fine.


03-Oct-2001 01:23

This is in response to [email protected] posting of 04-Oct-2000 09:11:



Be extremely careful with this. This allows anyone to overwrite _any_
internal variables which may have been set during script initialization!!!
It is far better to do something like this:



$expected_vars=array("var1","var2","var3");

foreach($expected_vars as $key)

    if($HTTP_GET_VARS[$key])

      $$key=$HTTP_GET_VARS[$key];

i.e. populate the array expected_vars with exactly what you expect
first.



Michael

mail at michael-schams.de
08-Oct-2001 04:36

You've to add the sessionid manually, when using a refresh-META-Tag
(according to the note from [email protected], 18-Feb-2000). The
sessionid will NOT added automatically, even if --enable-trans-sid is on.
The following seems to work (without cookies):

--- snip ---
$refresh="
echo "<META http-equiv=\"refresh\" content=\"5;
URL=$refresh?".SID."\">\n";
--- snap ---

alex_at_anthropie_dot_com
23-Oct-2001 08:57

The manual should state that --trans-SID now (4.0.6) works with POST too.
No need to add a

<input type="hidden" name="PHPSESSID" value="<?=$PHPSESSID?>">

to all your POST forms for users without cookies, PHP does it for you. AFAIK, the only time you would need to explicitly echo SID would be for non <body> redirects, i.e. header(location: ) and Meta Refresh.


shelby_at_downloadfast_dot_com
23-Oct-2001 08:27

Bear in mind that the use of cookie for storing the session id, is global
to all open windows of client (browser).  Thus it is possible to post a
form from a page whose inputs do match the current state of the session,
which can cause unpredictable behavior.  IMO, the use of nocache by
default PHP sessions, is to try to mitigate this problem, but not
completely eliminate it.

Also the use of cookie global to all open windows, prevents multiple
simultaneous sessions per browser (each in own window).  Unless you record
an identifier in the POST or GET vars of the page, in which case you might
as well store the session id there instead.

In order to work around this problem with using cookie, pass the session
id along in the POST or GET vars.  Then you can turn caching back on.

One can imagine the case where some incorrect values are posted from an
out of sync page (window) and overwrite some crucial data in the session
or worse recorded permanently to database.

The use of cookie for session id is convenient but it is risky and
unpredictable.  From a practical view, the user may never attempt to open
a 2nd window on a session, but I am not going to risk my data on that
assumption.  Also I would like to re-enable the Back button (caching).

IMO the other weaknesses of using cookie is that you must rely on PHP's
--enable-trans-id for case where cookies are off, and as of 4.0.6 this
compile flag will not work in cases such as Header( Location: ),
Meta-refresh, Javascript client side programmed links, etc..  Before
4.0.6, it apparently did not work with POST forms.


03-Nov-2001 06:40

Another note about manually including SID.
You also have to manually include the SID in any JavaScript-generated
links.
I ran into this with onClick="window.location.href=..."
attributes in various tags.


06-Nov-2001 06:36

It appears the following is true:
If you session_register a variable (say testvar) and then use the same
name as a form variable, the session value (HTTP_SERVER_VARS['testvar'])
will no longer change as the post value (HTTP_POST_VARS['testvar']
changes.


19-Dec-2001 03:56

Be advised that starting with version 4.1, there is a new way to access and
register session variables through the $_SESSION['your_variable'] array.
As a bonus, you can skip the session_register('your_variable') function
call as this method does automatically register newly assigned variables.
see: 


17-Jan-2002 04:30

Here's a simple way to have Embperl like sessions. This consist in a
"special" variable (a hash) wich is persistent and holds all the
persistent data. In this case the easyest way is to take directly the
$HTTP_SESSION_VARS variable, and add a prepend.inc and append.inc files to
automaticly register and unregister variables like this:
---- prepend.inc ----
<?php
# In case you don't use sessions auto start
session_start();

foreach ( $HTTP_SESSION_VARS as $var => $val )
   $OLD_SESSION_VARS[] = $var;
?>
---- append.inc ----
<?php
foreach ( $OLD_SESSION_VARS as $var )
   if ( !isset( $HTTP_SESSION_VARS[$var] ) )
      session_unregister( $var );

foreach ( $HTTP_SESSION_VARS as $var => $val )
   session_register( $var );
----------
The add this files to your php.ini as auto_prepend and auto_append, and
that's it...
All you have to do to use a persistent variable is to use it in the
$HTTP_SESSION_VARS hash. Try this script out with your new prepend and
append files:
---- test.php ----
<?= $HTTP_SESSION_VARS["counter"]++ ?>
------------------
and refresh it several times.
To unregister a variable, just unset() it, like <? unset(
$HTTP_SESSION_VARS["counter"] ); ?>

Hope it helps! :)


25-Jan-2002 12:15

When i want to redirect a page to another one and i'm using a session i
have to start session -session_start()- in every page i redirect to. Why?
It must be a solution...


31-Jan-2002 03:21

For the people fearing local exploits there are to solutions in case you
are running under unix:

One would be to make every user (except the www-servers user) belong to a
group (say users) and make public_html owned by <user>.users and
chmod 705 -> people belonging to users have zero permissions but others
(including www server ) have read and execute.

Another possiblity (which looks cleaner :) is to have public_html (and
session directory with files handler) belong to group www (or something)
that only the web server belongs to and have them chmod 750. You need to
chown them with root account or sudo script or something though..

Now if you encrypt the session data, other users can't get the key from
your public_html. You can also have your home directory 705 (or 701) and
have web pages under it but nobody belonging to users-group could access
it. You should be doing this anyway on multi-user environments if you have
anything sensitive in your home directory.


03-Feb-2002 07:54

At the moment on windows using apache the support for sessions seems to be
bugy. PHP version 4.1.1


06-Feb-2002 05:23

In response to  
[email protected]
18-Dec-2001 09:56 
 
> Be advised that starting with version 
> 4.1, there is a new way to access and
> register session variables through the 
> $_SESSION['your_variable'] array.

Which is both entirely *not* backwards compatible with session_*() and
horribly broken as far as variable functions go.

In other words, if you are using an older version of 4.x and have already
written code using session_start(), session_register(),
session_is_registered(), and session_destroy(), your old code will not
work.

The workaround is, of course, to convert to $_SESSION[].  Which is nice if
you're not pressed for time. :-(

Also, even though $_SESSION[] appears to be an array of mixed type
variables, none of the variable functions appear to work (i.e. isset(),
empty(), unset(), is_*(), etc).  I haven't yet found a good workaround for
this.

php 4.1.0, apache 1.3.20, win32


08-Feb-2002 02:44

I can not for the life of me get $_SESSION to work properly with PHP 4.1.1
without using session_register . Either I've misunderstood something or
there's a bug in the documentation where it says "do not use
session_register...."


10-Feb-2002 02:35

Using sessions instead of cookies... well...

Browsers send you all the info you need, even with cookies off... 
it just doesn't accept yours.

Stick all the info in a database (like me) & drag it out whenever 
and if you have an ISP that's too mean to give you a database... 

append the info to a file in a CGI dir... & PHP, PERL, etc. can search

the same file... I do believe that sessions is the same thing...

SID attaches itself as an invisible argument to the URI... 
What happens if you already have your own arguement attached???

"Dear Sir, You can't see my free gifts without your cookies on".
that should do it... 

Brian


11-Feb-2002 08:47

for anyone in the need of a simple login script tutorial featuring
sessions, try here:


12-Feb-2002 10:41

The current documentation on the use of $_SESSION in favour of
session_register() omits to mention that registering your variables in the
manner:

$_SESSION['cheese']='salmon';

does *NOT* implicitly start a session in the way that you might expect:

session_register($cheese);

to. This is not mentioned in the documentation, and the statement about
not mixing use of $_SESSION and older session functions leads you to
believe it should be handled automagically. In fact you must explicitly
call session_start() before you assign/retrieve values to/from $_SESSION,
eg:

session_start();
if (!isset($_SESSION['loggedIn']))
{
  $_SESSION['loggedIn']=false;
}
elseif ($_SESSION['loggedIn'])
{
  #Extra code if user logged in
}

avbentem at hetnet.nl
19-Feb-2002 10:42

One addition to mystran's note:

:: make every user (except the www-servers
:: user) belong to a group (say users) and
:: make public_html owned by <user>.users
:: and chmod 705

True, to limit access from the Unix shell. However, if in php.ini
open_basedir is left to its default, then a simple PHP script (running
with the server's permissions) would reveal the code anyway. In fact, such
a script also reveals the session IDs in /tmp, as explained in the warning
of session.save_path above.

Arjan.

avbentem at hetnet.nl
19-Feb-2002 11:41

I just wrote:

:: a simple PHP script [..] would reveal the
:: code anyway

Note that if open_basedir is not strict enough, then one can even open
hidden files in the directories of other virtual hosts, like Apache's
.htaccess, with a simple PHP script. So, using 

    SetEnv MySecretKey xyz

in .htaccess and 

    getenv( 'MySecretKey' )

in a PHP script, is less secure than one may expect. Well, at least the
value would not be printed if the PHP source code is shown to a visitor
due to a misconfiguration of the web server... 

So, if one wants to grant the users access to /tmp then the server
administrator could

- create a directory /sessions
- make it accessible to the web server only
- set session.save_path to /sessions
- set open_basedir to ".:/tmp/"

Arjan.


19-Feb-2002 01:18

If you are running PHP with register_globals = on, and you ain't able to
turn it of, either beacuse you are not allowed to change this setting or
because of backwards-compatibility reasons, secure session handling is
somewhat complicated. I wrote this class as a workaround to deliver
secure, realtime sessionhandling under that circumstances:

<?php 

class mySession 
{ 
    var $s_vars = array(); 
    
    //start session with name $name 
    function mySession($name) 
    { 
        session_name($name); 
        session_start(); 
        
        //determine session variables 
        foreach($GLOBALS["HTTP_SESSION_VARS"] as $key =>
$value) 
            $this->s_vars[substr($key,10)] = $value; 
    } 
    
    //register session variable
    function setSessionVar($key, $value) 
    { 
        if(!session_is_registered("mySession_".$key)) 
            session_register("mySession_".$key); 
        $GLOBALS["mySession_".$key] = $value; 
        $this->s_vars[$key] = $value; 
    } 
    
    //return session variable
    function getSessionVar($key) 
    { 
        return $this->s_vars[$key]; 
    } 

    //initialize session
    function initSession($name, $pass) 
    { 
        //if input is complete, check if user exists in database
        if($name && $pass) 
        { 
            /*include a database login here if needed*/ 
            
            //querystring. change it to match your requirements... 
            $qst = sprintf("SELECT * FROM user WHERE login='%s' AND
pw='%s'", 
                addslashes(strtolower($name)), addslashes($pass)); 
            $res = mysql_query($qst) or die(mysql_error()); 
            
            //if user is found, register some variables. 
            if(mysql_num_rows($res) > 0) 
            { 
                $row = mysql_fetch_array($res); 
                
                //authentification
                $this->setSessionVar("login", true); 
                
                //you can register what ever you want...
                $this->setSessionVar("var1",
$row["value1"]); 
                $this->setSessionVar("var2",
$row["value2"]); 
            } 
        } 
    } 
    
    //kill session
    function killSession() 
    { 
        session_destroy(); 
        $this->s_vars = array(); 
    } 
} 

?>

To use this class, simply create a new object $login = new
mySession("name"); instead of calling session_start(); Now you
can register new variables, and change their values at any time using
$login->setSessionVar("name"). You can get the value of any
variable registered before using $login->getSessionVar("name).
E.g. if you want to confirm whether the user is logged in:
if($login->getSessionVar("login")) { code }. That should make
the usage of sessions under register_globals a little more worry-free :)

Comments? Send a mail!

Tim

avbentem at hetnet.nl
20-Feb-2002 11:49

There's another good reason to use $HTTP_SESSION_VARS or $_SESSION rather
than relying on the global variables: an administrator could change the
php.ini directive "variable_order". Although changing it would
be strange, it would suddenly change the behavior of your PHP code.

Arjan.



variables_order  string

Set the order of the EGPCS (Environment, GET, POST, Cookie, Server)
variable parsing. The default setting of this directive is
"EGPCS". Setting this to "GP", for example, will cause
PHP to completely ignore environment variables, cookies and server
variables, and to overwrite any GET method variables with POST-method
variables of the same name.


02-Mar-2002 10:33

At the end of a session if I want to perform some housekeeping operation
(like dropping of temporary tables, etc.). Right now these operations are
done at the time of logging out. But what if the user doesn't logout. Is
there any way determining the expiry of a session and then immediately
performing the housekeeping activities?


08-Mar-2002 06:48

Here's one useful function to consider  (still using the old style HTTP_
arrays).  This is useful because the GET-based session fallback mode
doesn't append session ids to header calls.  However, you might want to
maintain your session ids across local redirects.

<pre>
function localRedirect("url")
{
   GLOBAL $HTTP_COOKIE_VARS;
   if (isset($HTTP_COOKIE_VAR["PHPSESSID"]))
     header("Location: $url");
   else
     header("Location: $url" ."?" . SID);
}

This allows a much cleaner fallback when the cookie was rejected by the
user.  The only thing remaining that is non-transparent is that I can't
seem to get the "Accept Cookie" dialog to not pop up on every
succeeding page if the user declines the first one.


20-Mar-2002 02:24

If u try to save values from a form in session_vars its important that the
name of the session_var is different from the name of the formfield. if
its the same, u ll get some *** errors and u spend hours for searchin ur
mistake ;-)

extremly simplified:

##file1.php:
<form .... target="file2.php">
<input .... name="fhugo">
</form>

##file2.php:
<? session_start();
    session_register('hugo');
    # save value of formfield in sessionvar  
    #remove everything from $hugo, only  a-z and A-Z is allowed
    $hugo = ereg_replace("[^a-zA-Z]","",$fhugo);
   # go to next page
   header("Location: file3.php");
?>

## file3.php:
<? session_start();
    echo "hugo is $hugo";
?>
<a href="file1.php">start again</href>

i use this for savin some options for a database search that uses several
forms and scripts


20-Mar-2002 03: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.


21-Mar-2002 12:18

Commenting what [email protected] gave us on 25 August 2000, I'd
add pretty obviously (but then I did have to check it for myself, so maybe
someone else out there has too) that you can take this code, stuff it in
another file and just call said file at the end of your Web page with
include() or require() depending on your poison. (Of course, since it
includes function definitions, include_once() and require_once() would be
recommended, but you already had figured that out yourself.)


01-Apr-2002 11:30

Using PHP 4.1.2 on IIS 5.0, Win2k, haven't migrated app yet to Linux
(later!)
Managed to eventually get the sessions to work as follows.
In the php.ini, session.auto_start = 1 
Then without a session_start(); 
$xvar = "something" ;
Use
session_register("xvar");
then u CAN retrieve from a later page using the new way:
$var = $_SESSION["xvar"] ;
also without session_start();
even doing a var_dump($_SESSION); seems to work at least some of the time!

The odd thing is that storing vars using the new way:
$_SESSION["xvar"] = "something";
will save only for the CURRENT page, this gets lost when moving on to the
next page!
best regards
Mike


07-Apr-2002 10:31

Dear all,
The ultimate answer to the SESSION problems appears to be the new version
4.2.0 (currently waiting as release candidate) in that version it all
seems to work just as I would have expected, without work-arounds.

$_SESSION["var"] = "fred";

a few pages later ....

$var2 = $_SESSION["var"];
echo $var2;

 ...prints out "fred" !
Also the session_destroy() works - you can even watch the file being
deleted.
best regards
Mike


11-Apr-2002 03:03

When using the transparent SID functionality, be warned that if you are
using zlib.output_compression = On in your php.ini to compress all your
output then the automatic insertion of SIDs into relative href's and into
forms will NOT work.
I presume this is because the parser which does the insert of the SIDs is
run after the web page is compressed.

Since compression makes the site run massively faster (try
www.forestknoll.com), for instance a packet dump of one page without
compression is 38k and with compression it is 4.9k, I have switched the
SID functionality off.

Fortunately I use http basic realm authentication over ssl, which to me is
the best session handler of all, it is impossible to hijack and it works
with all browsers.


12-Apr-2002 06:22

The following code fragment works around the fact that my PHP4.1.2
(iis/cgi) does not work as advertised. You can use it for whatever other
reason you choose.

# Include this code somewhere if you're having trouble with $_SESSION not
# seeming to work as advertised.

session_start();

function Work_around_session_bogosity() {
	foreach(array_keys($GLOBALS['HTTP_SESSION_VARS']) as $k) {
		if (!isset($_SESSION[$k])) session_unregister($k);
	}
	
	foreach($_SESSION as $k=>$v) {
		if (!session_is_registered($k)) session_register($k);
		$GLOBALS['HTTP_SESSION_VARS'][$k] = $v;
		$GLOBALS[$k] = $v;
	}
}

register_shutdown_function('Work_around_session_bogosity');


16-Apr-2002 06:19

If you use session_trans_sid, the sessionid will not be transmitted if you
use a meta refres
(echo "<META HTTP-EQUIV=\"Refresh\"
CONTENT=\"3;URL=index.php\">";)

this will forward you to index.php after 3 seconds, but it will not
transmit your session id

use this:
echo "<META HTTP-EQUIV=\"Refresh\"
CONTENT=\"3;URL=index.php?PHPSESSID=" .session_id()
."\">";

replace PHPSESSID with your php session name (session_name)

rene_AT_cola.cc
26-Apr-2002 06:10

The time it takes for a session to expire is 1440 seconds = 24 minutes by
default.
To change this to, say 15 minutes:
ini_set("session.gc_maxlifetime", "900");


02-May-2002 04:32

Using PHP 4.2.0, Apache 1.3.24 and Windows 2000, I'm experiencing problems
with session variables. Once register_globals is off, I'm trying to use
$_SESSION to read/write a session variable.
My example have two files: page1.php and page2.php.

--- page1.php -----------------------
<?

session_start();

$_SESSION['sess_var'] = "Hello World!";

echo "The content of session variable is
".$_SESSION['sess_var']."
"; ?> <a href = "page2.php">Next page</a> ------------------------------------- This file outputs correctly what is expected. But next file does not... --- page2.php ----------------------- <? session_start(); if (isset($_SESSION['sess_var'])) { $sess_var = $_SESSION['sess_var']; echo "The content of \$sess_var is $sess_var
"; } else echo "The session variable does not exist!
"; ?> ------------------------------------- Here I recieve the message about session variable non-existance. Can anyone help me?


05-May-2002 09:21

Here is the output of 2 hours of stress.

If you use the sessions_mysql function library or the real path style of
sessions (default on php installation)... whenever you want to manually
delete a session -- be SURE your session has not started yet.

Meaning, session_start() has not ran, or in the php.ini you dont have a
auto start; otherwise you will have to stop it, delete your session and
then start it again.

Regards,
OS


07-May-2002 09:27

BEGINNERS: [like me :)]

To use sessions, follow these easy instructions that I worked up for my
friend after I finally got sessions working.

On the page that starts the session (the page you are passing the
variable(s) from, at the very, very top (ABOVE ANY HTML TAGS) type:

<?php
session_start();
....rest of code follows...

Then at the point where you would like the variable to be sent (it will be
sent as it is, at that point! so if you modify it later, the effects WILL
NOT be sent), add this code (in php):

session_register('variable_name');

You can use this line of code for as many variables as you want, replacing
variable_name with its actual name, but leaving the quotes.

Now, on the recieving end. Create some kind of link to the .php file that
recieves these variables. When the user clicks on the link, the info will
be sent.

At the very, very top of the recieving file (once again, ABOVE ANY HTML),
add:

<?php
session_start();
session_register('variable_name');
...rest of code...

This time, register the variables at the very top. Repeat the register
code as many times as necessary. Now, the info will be loaded into those
variables, and they will be ready to use!

Good luck!                      - BadAssFrey


07-May-2002 11:53

BEGINNERS:

I want to correct one thing, and add another.

Firstly, if you change a variable after you register it (using
session_register('variable_name'), the effects WILL be passed to the next
page. My mistake, so sorry.

Second, my friend's code still didn't work so I looked at it. His problem
was how he registered his variable:

session_register($content[1]); // WRONG!!!

You shouldn't put the dollar sign, and the variable name should be put in
quotes, like this:

session_register('content'); // RIGHT!!!

He really wanted to pass only the second part of the array content, but
since I really don't know how, I would recommend sending the whole thing.

Good luck!                   -BadAssFrey


08-May-2002 10:45

//-
session_register('content'); // RIGHT!!!
He really wanted to pass only the second part of the array content, but
since I really don't know how, I would recommend sending the whole thing.
Good luck!                   -BadAssFrey
//-

$tmp=$content[1];
session_register('tmp');

should work ;)

-minde

Joerg Aldinger
10-May-2002 10:26

After having had a hard time with a provider who has --enable-trans-sid
disabled, i've created this little piece of code to automatically add the
session id to internal links and forms. It assumes you have the whole page
loaded into $page. (Remove whitespaces from $search when copying!)

$mySID = session_name().'='.session_id();
$search = array(
    "'(<a[^>]*href=\"
        (?!)
        [^?\">]*\\?[^\">]*)\"'iU",
    "'(<a[^>]*href=\"
        (?!)
        [^?\">]*)\"'iU",
    "'(<form[^>]*action=\"
        (?!)
        [^?\">]*\\?[^\">]*)\"'iU",
    "'(<form[^>]*action=\"
       (?!)
       [^?\">]*)\"'iU");
$replace = array(
    '\\1&'.$mySID.'"',
    '\\1?'.$mySID.'"',
    '\\1&'.$mySID.'"',
    '\\1?'.$mySID.'"');
$page = preg_replace($search, $replace, $page);


12-May-2002 04:58

Just FYI:  If you have multiple php scripts running simultaneously (for
example, in different frames or browser windows) and they use sessions,
they won't execute concurrently.  The various scripts will block until
they have exclusive access to the session variables.  If all your scripts
finish quickly (as most do) you probably won't notice.  But if you have
any long-running scripts (e.g. system() or passthru() calls that take a
while to finish) you may see some pauses in page rendering.  This is well
documented in session_write_close(), but might warrant mentioning more
prominently here.
HTH.
ed


14-May-2002 12:57

In reference to the above note:

############################

When using Header("Location: url"), you must add a
"?".sid to the end or your session will not carry to the next
page. i.e. Header("Location: url?".sid)  :(

############################

This doesnt seem to be the case in PHP 4.20, It does in fact work fine.

twocandles3000@hotmail
14-May-2002 05: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.

php 4.2.0 and 4.2.1, Apache 1.3 and W2K Pro.

17-May-2002 07:07
The description states "As of PHP 4.1.0, $_SESSION is available as
global variable just like $_POST, $_GET, $_REQUEST and so on. Not like
$HTTP_SESSION_VARS, $_SESSION is always global. Therefore, global should
not be used for $_SESSION. "

However, this is not the case.  Try as I might, I could not get my
registered session variables.  I was using verion 4.1.2.  I just
downloaded 4.2.1 and the same code works perfectly.  If you're having the
same problem, try upgrading.


25-May-2002 07:02

4.1.2 under Windows cannot handle sessions properly, if register_globals is
off. The "count++" sample did not work for me until I upgraded
to 4.2.1


25-May-2002 08:01

I wrote a tiny "shopping-cart" code when I was learning PHP
sessions. (Use ++ instead of =1 to allow more than one product of a kind
in the cart). 

<?php
session_start();
// - Add
if( isset( $_GET['ADD'] ) ) {
	$_SESSION['aBasket'][$_GET['ID']] = 1;
	}
// - Remove
if( isset( $_GET['DEL'] ) ) {
	unset($_SESSION['aBasket'][$_GET['ID']]);
	}
// - Remove All
if( isset( $_GET['EMP'] ) ) {
	unset($_SESSION['aBasket']);
	}
// - Show
if( isset( $_SESSION['aBasket'] ) ) {
	foreach ( $_SESSION['aBasket'] as $key=>$val ) {
		echo "$key ";
		}
	}
?>
<form>
Product:
<input type="text" name="ID">
<input type="submit" name="ADD"
value="Add">
<input type="submit" name="DEL"
value="Del">
<input type="submit" name="EMP"
value="Empty">
</form>

Gregory


26-May-2002 06:50

REGARDING:

" The <?=SID?> is not necessary, if  --enable-trans-sid was
used to compile PHP.

Huomaa: Non-relative URLs are assumed to point to external sites and hence
don't append the SID, as it would be a security risk to leak the SID to a
different server."

This is a crock of shit.

So its a security risk to leak the SID?

Then how come the APACHE logs on other servers are showing up the session
ID for my users? WHEN I HAVE NO SESSION ID IN THE LINK!!!

Because the Session ID is still forwarded in the REFERRER!!!!!

This is HUGE SECURITY HOLE and there is no excuse that this has been known
and is not thrown in peoples face on this page.

Sincerely,
Mr. My Site Got Hacked.

READ THIS:


The HTTP_REFERER problem

If your site uses the wonderful URL rewriting feature then you have one
more thing to worry about. Every click to an external site will reveal the
session id to it. It is not that the problem is in the PHP code, the URL
rewriting code does not append session ids to absolute URLs. But, the
browser will send the URL of the page to the external site in the
HTTP_REFERER header.

Solving this problem requires some discipline. Instead of sending people
to external sites directly, send them through a simple script. You also
need to reference this script through an absolute URL to a



My first version of the script looked like this:

<? header('Location: ' . $HTTP_SERVER_VARS['QUERY_STRING']) ?>

But I found out that Netscape uses the URI of the original page (the one
containing the SID) when you use redirection. Oh well, another way is to
use the META refresh technique:

<meta http-equiv="refresh" content="0; url=<? echo
$HTTP_SERVER_VARS['QUERY_STRING']?>">

Be warned that this will completely hide the referrer information. If you
want other sites to know that you are sending people their way, use the
Javascript redirection technique instead. "


31-May-2002 01:32

somebody might need this (like me)

It automagically registers the request's $_POST vars as a $_SESSION var if
they do not already exist and fills them :)

if (!empty($_POST))
{
	foreach($_POST as $key=>$value)
		{
		 if (!session_is_registered("$key"))
			{
			 session_register("$key");
			 $_SESSION["$key"] = $value;
			}
		}
}


10-Jun-2002 05:48

The method of passing the session id as a URL (GET) argument lends it self
more  to session hijacking, since the session id will appear in proxy
server logs.


12-Jun-2002 02:31

If you only want to use cookies to preserve the session and don't want to
send a header(location:URL) with the sessiond id, make sure that the
session_start() is called on any page before the header(location: ) is
sent.  That's because if the session_start() is called for the first time
at the same time as the header(location: ) the cookie is not set by the
browser.  After the cookie is already set on a page without the redirect,
you can use header(location:)'s all you want.


15-Jun-2002 01:10

The person who said that you have to add the session ID as a GET variable
when doing a header("Location: <page>") call doesn't seem
to be right, it works fine without on my system.


16-Jun-2002 11:48

I wrote a login page for a site in PHP 4.1.2 and if the login was
successful I was using a Header("Location: ") to redirect the
user to another page. The problem I noticed is that the Session wasn't
passed to the redirected page. I tried using a Header("Location:
myfile.php".$PHPSESSID) but no result. I solved this mystery by using
a :
<script language="javascript">
     location.href="myfile.php";
</script>
This is not so elegant but it works !
Hope it helps


20-Jun-2002 06:15

Try using the PHP constant SID if you are using the sessions functions.
header("Location:myfile.php?".SID);
This should work.

24-Jun-2002 11:48
Addendum to [email protected]:
The "s:n" stuff in the session variables means: the type of the
variable is a string (s) with n characters.


27-Jun-2002 10:51

For automatic session initialization on every page, you have to set the
flag session.auto_start = 1 in php.ini. And you will get a warning in row
0, php couldn't open the session file, when your path for session files is
set relative like this: session.save_path = ..\tmp, which can work
perfectly with the session_start() functions.

If changing autostart to 1 und having a relative save_path for sessions,
the absolute directory path changes. That's because the path no longer
refers to the current scripting file (where sesson_start() was executed
before) but the system itself.

Using Apache the tmp directory is to add to the folder "Apache
Group". Than it works again.


06-Jul-2002 02:06

I think I've come up with a practical "session intrusion/hijack
detector" (where someone discovers a Session ID and tries to gain
access).

1. create a session var called "sreqs" (server requests)
2. create a cookie called "creqs" (client requests)
3. On each page you:
  a: increment sreqs using PHP
  b: increment creqs using JavaScript
  c: compare sreqs to creqs with JavaScript in client or PHP in server.
  d: if they are not equal, some else is tugging your chain!

As creqs is a cookie, it is returned to the server, so it could issue the
warning.

The key point here is that the client and server keep separate counts. A
second broswer will ALWAYS cause sreqs to go out of sync - even if they
"sniff" the count value, they can't stop sreqs incrementing and
they can't  change the owner's creqs cookie. They can look but the cannot
touch (and where's the fun in that!).

If the warning is server based (the creqs cookie from the intruder will
almost certainly be wrong), it could log the new IP and send the details
to the owner and service provider.

I've tested it on my prototype site and it certainly works using a test
"URL settable" session ID to simulate an intrusion using 2
browsers.

It can be thrown out of sync by partial page loads or STOPs but I put the
JavaScript in the HEAD section to reduce the chances of this.

Can anyone see any flaws in my logic or could this be a solution?

Neil Munro.

Catalyse Networks Limited.

add a note about notes
previoussesam_settransactionsession_cache_expirenext
Last updated: Tue, 11 Jun 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Mon Jul 8 08:17:45 2002 CEST