|
|
XCII. Munkamenet kezel� f�ggv�nyek
A PHP munkamenet kezel�se lehet�v� teszi adatok meg�rz�s�t az
egym�st k�vet� oldal lek�rdez�sek k�z�tt. Ez k�pess� tesz
m�g testreszabhat�bb oldalak k�sz�t�s�re.
Ha ismered a PHPLIB munkamenet kezel�s�t, sok hasonl�s�got
fogsz felfedezni a PHP munkamenet kezel� f�ggv�nyeit illet�en.
Minden webhelyedre l�togat� egy-egy egyedi azonos�t�t kap,
az �gynevezett munkamenet azonos�t�t (session azonos�t�t).
Ez vagy egy s�tiben (cookie) t�rol�dik a l�togat� g�p�n,
vagy az URL-ben k�zlekedik oldalr�l oldalra.
A munkamenet t�mogat�s lehet�v� teszi tetsz�leges sz�m� v�ltoz�
meg�rz�s�t a PHP oldal lek�rdez�sek k�z�tt. Ha egy l�togat�
�rkezik webhelyedre, h�romf�lek�ppen kezd�dhet el, vagy folytat�dhat
a munkamenete. Mindh�rom esetben a PHP egy munkamenet
azonos�t� �rkez�s�t v�rja. Ha nem �rkezik, �j munkamenetet
ind�t.
Ha a session.auto_start be van kapcsolva, a PHP automatikusan
megkezdni / folytatja a munkamenetet. Ha ez nincs bekapcsolva,
akkor k�zvetlen�l a session_start()
f�ggv�nnyel, vagy k�zvetve a session_register()
f�ggv�nnyel tudod a munkamenetet folytatni / megkezdeni.
Ha egy �rv�nyes azonos�t� �rkezett, a kor�bban be�ll�tott
munkamenet k�rnyezet vissza�ll�t�sra ker�l.
Minden a munkamenethez rendelt v�ltoz� szerializ�l�dik a
PHP oldal fut�s�nak befejez�d�sekor. A nem defini�lt,
de munkamenethez rendelt v�ltoz�k a k�s�bbi folytat�sokban
nem j�nnek �jb�l l�tre.
A track_vars �s
register_globals
ini be�ll�t�sok befoly�solj�k a munkamenet v�ltoz�k t�rol�s�nak
�s vissza�ll�t�s�nak m�dj�t.
Megjegyz�s:
A PHP 4.0.3 verzi�t�l kezdve a track_vars mindig
be van kapcsolva, kikapcsol�s�ra nincs m�d.
Megjegyz�s:
A 4.1.0 verzi�t�l kezdve a $_SESSION szuperglob�lis
v�ltoz� rendelkez�sre �ll, csak�gy mint a $_POST,
$_GET, $_REQUEST �s �gy tov�bb.
A $HTTP_SESSION_VARS v�ltoz�t�l elt�r�en a
$_SESSION mindig el�rhet� (szuperglob�lis).
Ez�rt a global kulcssz�val nem szabad egy�tt
haszn�lni a $_SESSION v�ltoz�t.
Ha a track_vars be
van kapcsolva, �s a register_globals
ki van kapcsolva, csak a $HTTP_SESSION_VARS
asszociat�v t�mb elemei a munkamenet v�ltoz�k. A vissza�ll�tott
munkamenet v�ltoz�k is csak a $HTTP_SESSION_VARS
t�mbben lesznek megtal�lhat�ak.
P�lda 1.
V�ltoz� bejegyz�se a munkamenetbe a track_vars
bekapcsolt �llapot�ban.
<?php
if (isset($HTTP_SESSION_VARS['szamlalo'])) {
$HTTP_SESSION_VARS['szamlalo']++;
}
else {
$HTTP_SESSION_VARS['szamlalo'] = 0;
}
?> |
|
A $_SESSION v�ltoz� haszn�lata (vagy
a $HTTP_SESSION_VARS v�ltoz� haszn�lata
PHP 4.0.6 vagy r�gebbi verzi� eset�n) javasolt biztons�gi
�s olvashat�s�gi szempontok miatt. A
$_SESSION vagy
$HTTP_SESSION_VARS haszn�lat�val nincs sz�ks�g
a session_register()/session_unregister()/session_is_registered()
f�ggv�nyekre. A programoz�k �ppen �gy dolgozhatnak a munkamenet
v�ltoz�kkal, mint a "norm�lis" v�ltoz�kkal.
P�lda 2.
V�ltoz� bejegyz�se a munkamenetbe a $_SESSION t�mbbel.
<?php
// Haszn�ld a $HTTP_SESSION_VARS t�mb�t PHP 4.0.6 vagy r�gebbi verzi�ban
if (!isset($_SESSION['szamlalo'])) {
$_SESSION['szamlalo'] = 0;
} else {
$_SESSION['szamlalo']++;
}
?> |
|
P�lda 3.
V�ltoz� bejegyz�s t�rl�se a $_SESSION t�mbbel.
<?php
// Haszn�ld a $HTTP_SESSION_VARS t�mb�t PHP 4.0.6 vagy r�gebbi verzi�ban
unset($_SESSION['szamlalo']);
?> |
|
Ha a register_globals
be van kapcsolva, akkor minden glob�lis v�ltoz� lehet munkamenet
v�ltoz�k�nt regisztr�lva, �s a munkamenet k�s�bbi folytat�saiban is
l�tre fognak j�nni glob�lis v�ltoz�kk�nt a bejegyzett v�ltoz�k.
Mivel ebben az esetben a PHP-nek tudnia kell, hogy mely glob�lis
v�ltoz�k bejegyzett munkamenet v�ltoz�k is egyben, a programoz�nak
a session_register() f�ggv�nyt kell haszn�lnia. Eml�keztet�k�nt a
$HTTP_SESSION_VARS/$_SESSION
t�mb�k haszn�latakor nincs sz�ks�g a session_register() f�ggv�nyre.
P�lda 4.
V�ltoz� bejegyz�se a register_globals
bekapcsolt �llapota mellett.
<?php
if (!session_is_registered('szamlalo')) {
session_register("szamlalo");
$szamlalo = 0;
}
else {
$szamlalo++;
}
?> |
|
Ha mind a track_vars, mind a
register_globals
be�ll�t�sok be vannak kapcsolva, a glob�lis v�ltoz�k �s a
$HTTP_SESSION_VARS/$_SESSION
t�mb�k elemei ugynazokra az �rt�kekre fognak mutatni a m�r
bejegyzett v�ltoz�kat illet�en.
Ha a programoz� a session_register() f�ggv�nyt haszn�lja munkamenet
v�ltoz�k bejegyz�s�re, akkor ebben az esetben a
$HTTP_SESSION_VARS/$_SESSION
t�mb�kben nem fog megjelenni ez a v�ltoz� a k�vetkez� munkamenet
folytat�sa el�tt (azaz a k�vetkez� PHP program fut�s el�tt).
K�tf�lek�ppen "k�zlekedhet" a munkamenet azonos�t�:
S�ti form�j�ban
URL / �rlap param�terben
A munkamenetkezel� modul mindk�t form�t t�mogatja. A s�tik
optim�lisak, de sajnos nem megb�zhat�ak (sokan nem fogadj�k
a s�tiket), ez�rt nem lehet r�juk biztons�ggal �p�teni.
A m�sodik m�dszer az azonos�t�t k�zvetlen�l az URL-ekbe
�s �rlapokba helyezi.
A PHP k�pes ezut�bbi azonos�t� terjeszt�st �tl�tsz�an v�gezni, ha az
--enable-trans-sid opci�val fod�tottad.
Ha ezt az opci�t bekapcsolod, a relt�v URL-ekhez �s �rlapokhoz
automatikusan hozz�teszi a PHP a munkamenet azonos�t�t. Alternat�v
m�dszerk�nt haszn�lhatod a SID konstanst, ami
defini�lt, ha a kliens nem k�ldte vissza a megfelel� s�tit. A
SID vagy session_name=session_id
(munkamenet n�v, munkamenet azonos�t�) form�tum�, vagy egy �res
karektersorozat.
A k�vetkez� p�lda egy v�ltoz� bejegyz�st, �s egy k�vetkez� oldalra
mutat� link k�sz�t�s�t mutatja,
P�lda 5. Egy l�togat� �ltal leh�vott oldalak sz�ml�l�sa <?php
if (!session_is_registered('szamlalo')) {
session_register('szamlalo');
$szamlalo = 1;
}
else {
$szamlalo++;
}
?>
�dv l�togat�, eddig <?php echo $szamlalo; ?> alkalommal
l�ttad ezt az oldalt.<p>
<?php
# Az <?php echo SID?> sz�ks�ges, hogy a munkamenet azonos�t�t
# meg�rizz�k abban az esetben is, ha a l�togat� nem fogadja
# a s�tit. (<?=SID?> haszn�lhat�, ha a r�vid tagek enged�lyezettek)
?>
A tov�bbl�p�shez <A HREF="kovoldal.php?<?php echo SID?>">kattints ide</A>. |
|
A <?=SID?> nem sz�ks�ges, ha az
--enable-trans-sid opci�val
ford�tottad a PHP-t.
Megjegyz�s:
A nem relat�v hivatkoz�sok felt�telezetten k�ls� oldalakra
mutatnak, ez�rt nem eg�sz�lnek ki automatikusan a SID-el.
Komoly biztons�gi probl�m�kat okozna, ha a SID-ek
elker�ln�nek egy m�sik kiszolg�l�hoz.
A munkamenethez tartoz� adatok �llom�nyokban t�rol�dnak.
Ha adatb�zisban, vagy m�s t�rol� eszk�z�n szeretn�d r�gz�teni
a munkamenethez tartoz� adatokat, a
session_set_save_handler() f�ggv�nyt
kell haszn�lnod a saj�t t�rol� f�ggv�nyeid bejegyz�s�hez.
A munkamenet kezel� f�ggv�nyek sz�mos be�ll�t�si lehet�s�get
biztos�tanak, amiket a php.ini �llom�nyban helyezhetsz el.
Egy r�vid �ttekint�s k�vetkezik.
A session.save_handler be�ll�t�s adja
meg a haszn�lt t�rol�s kezel�t, ami a munkamenet adatok
elment�s�re, �s visszakeres�s�re szolg�l. Az alap�rt�ke
files.
A session.save_path be�ll�t�s az a param�ter,
amit a t�rol�s kezel� megkap. Ha az alap�rtelmezett �llom�ny
kezel�t haszn�lod, ez a munkamenetek t�rol�s�ra haszn�lt
ideiglenes �llom�nyok k�nyt�r�nak el�r�si �tja. Alap�rtelmez�se
/tmp. Ha a session.save_path
m�lys�ge t�bb mint kett�, az automatikus szem�t takar�t�s
nem fog m�k�dni.
Figyelem |
Ha ezt az �rt�ket egy mindenki �ltal olvashat� k�nyvt�rra
�ll�tod (mint az alapbe�ll�t�s� /tmp),
akkor a kiszolg�l�n l�v� t�bbi felhaszn�l� el tudja kapni
a munkameneteidet a k�nyvt�rban l�v� �llom�nyok neve �s
tartalma alapj�n.
|
A session.name a munkamenet neve, amit
a PHP a s�ti be�ll�t�sakor, az URL / �rlap param�terek
felv�telekor �s a munkamenet folytat�sakor haszn�l. Csak
alfanumerikus karaktereket tartalmazhat. Alap�rt�ke
PHPSESSID.
A session.auto_start be�ll�t�s adja meg,
hogy a PHP kezdjen-e / folytasson-e minden PHP oldal
futatt�sn�l automatikusan munkamenetet. Alap�rt�ke
0 (kikapcsolt).
A session.cookie_lifetime a be�ll�tott
s�ti �lettartalm�t szab�lyozza m�sodpercekben megadva.
A nulla �rt�k azt jelenti, hogy "am�g a b�ng�sz�t be
nem z�rj�k". Alap�rt�ke �ppen 0.
A session.serialize_handler a
szerializ�l�shoz haszn�lt kezel� nev�t adja meg.
Jelenleg egy be�p�tett PHP form�tum (php
n�ven) �s egy WDDX form�tum t�mogatott
(wddx n�ven). A WDDX form�tumhoz
sz�ks�ges, hogy a WDDX t�mogat�s a PHP-be legyen
ford�tva. L�sd WDDX.
Alap�rt�ke a be�p�tett php kezel�.
A session.gc_probability megadja, hogy
mekkora val�sz�n�s�ggel indul el a gc (garbage collection -
szem�tgy�jt�s) az egyes PHP lek�rdez�sekkor. Az �rt�ket
sz�zal�kban kell megadni. Alap�rt�ke 1.
A session.gc_maxlifetime megadja, hogy
h�ny m�sodperc eltelt�vel tekinti a szem�tgy�tjt� szem�tnek,
�s eltakar�tand�nak a munkamenet adatokat.
A session.referer_check azt a
r�sz-karaktersorozatot tartalmazza, amit minden HTTP
Referer fejl�cben keresni szeretn�l a munkamenetek m�g
biztons�gosabb azonos�t�sa c�lj�b�l. Ha a megadott
r�sz-karaktersorozatot nem tal�lja meg a PHP a Refererben,
a k�ld�tt munkamenet azonos�t�t nem fogja elfogadni.
Alap�rt�ke az �res karaktersorozat.
A session.entropy_file egy el�r�si utat
hat�roz meg ahhoz az "�llom�nyhoz", amit a PHP k�ls� entr�pia
forr�snak haszn�l a munkamenet azonos�t� el��ll�t�sakor.
Ez lehet p�ld�ul /dev/random vagy
/dev/urandom. Ezek sok Unix rendszeren
el�rhet�ek.
A session.entropy_length az olvasott
byte-ok sz�m�t adja meg, amennyit a fent eml�tett
�llom�nyb�l olvas a PHP. Alap�rt�ke 0
(kikapcsolt).
A session.use_cookies hat�rozza meg,
hogy a PHP haszn�l-e s�tiket a munkamenet azonos�t�
t�rol�s�ra a kliens oldalon. Alap�rt�ke
1 (enged�lyezett).
A session.cookie_path azt az el�r�si
utat hat�rozza meg, amit a munkamenet s�tiben be�ll�t
a PHP. Alap�rt�ke /.
A session.cookie_domain azt a domain
�rt�ket hat�rozza meg, amit a PHP a munkamenet s�tiben
be�ll�t. Alap�rt�ke semmi.
A session.cache_limiter azt a cache met�dust
hat�rozza meg, amit a munkamenet oldalakra alkalmazni kell.
Lehets�ges �rt�kei: none, nocache, private, private_no_expire �s
public. Alap�rt�ke nocache.
A session.cache_expire megadja, hogy h�ny
percig legyen aktu�lis a cache-ben egy munkamenetet haszn�l�
oldal. Ennek nincs hat�sa, ha nocache m�dot v�lasztasz.
Alap�rt�ke 180.
A session.use_trans_sid szab�lyozza, hogy
az �tl�tsz� SID hozz�ad�s be van-e kapcsolva vagy nincs.
Ehhez sz�ks�ges, hogy a
--enable-trans-sid opci�val
ford�tsd kor�bban a PHP-t. Alap�rt�ke 1
(enged�lyezett).
Az url_rewriter.tags adja meg, hogy mely
HTML elemeket kell �t�rni, ha a munkamenet azonos�t�k
�tl�tsz� elhelyez�se be van kapcsolva. Alap�rt�ke
a=href,area=href,frame=src,input=src,form=fakeentry
Megjegyz�s:
A munkamenetek t�mogat�sa a PHP 4.0 verzi�ban jelent meg.
User Contributed Notes Munkamenet kezel� f�ggv�nyek |
|
[email protected]
19-Feb-2000 12: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) :(
|
|
[email protected]
30-Jun-2000 04: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:
|
|
[email protected]
08-Aug-2000 11: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)
|
|
[email protected]
13-Aug-2000 02: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()!
|
|
[email protected]
20-Aug-2000 02: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).
|
|
[email protected]
30-Aug-2000 05: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 09: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.
|
|
[email protected]
16-Oct-2000 12: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."
|
|
[email protected]
11-Dec-2000 01: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.
|
|
[email protected]
15-Dec-2000 11: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.
|
|
[email protected]
16-Dec-2000 02: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.
|
|
[email protected]
28-Dec-2000 03: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.
|
|
[email protected]
13-Mar-2001 05: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.]
|
|
[email protected]
03-May-2001 05: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.
|
|
[email protected]
10-May-2001 11: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
|
|
[email protected]
03-Jun-2001 07: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.
|
|
[email protected]
19-Jul-2001 05: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...
|
|
[email protected]
21-Jul-2001 05: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]; }
?>
|
|
[email protected]
01-Aug-2001 12: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
|
|
[email protected]
03-Oct-2001 02: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
|
|
[email protected]
03-Nov-2001 07: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.
|
|
[email protected]
17-Jan-2002 05: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! :)
|
|
[email protected]_SPAM.net
11-Feb-2002 09:47 |
|
for anyone in the need of a simple login script tutorial featuring
sessions, try here:
|
|
[email protected]
19-Feb-2002 02: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 12: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.
|
|
[email protected]
08-Mar-2002 07: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.
|
|
[email protected]
20-Mar-2002 03: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
|
|
[email protected]
20-Mar-2002 04: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&PHPSESSID=12345678abcde"></go>
It�s
safety include the line: ini_set ( "arg_separator",
"&");
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.
|
|
[email protected]
16-Apr-2002 07: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 07: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");
|
|
[email protected]
05-May-2002 10: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
|
|
Joerg Aldinger
10-May-2002 11: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);
|
|
[email protected]
12-May-2002 05: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
|
|
twocandles3000@hotmail
14-May-2002 06: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 08: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.
|
|
[email protected]
25-May-2002 09: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
|
|
session_id@my_site_got_hacked.com
26-May-2002 07: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. "
|
|
[email protected]
31-May-2002 02: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; } } }
|
|
[email protected]
10-Jun-2002 06: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.
|
|
[email protected]
12-Jun-2002 03: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.
|
|
[email protected]
20-Jun-2002 07:15 |
|
Try using the PHP constant SID if you are using the sessions
functions. header("Location:myfile.php?".SID); This should
work.
|
|
Tyler Larson
02-Aug-2002 08:02 |
|
Some of the examples listed in the text of this page are a bit misleading.
The code as it is will not behave as expected.
## THIS WON'T
WORK <?php if (!session_is_registered('count')) {
session_register("count"); $count = 0; } else {
$count++; }
print $count; ?>
The code should
instead read as follows:
## this code WILL
work <?php session_start(); if
(!session_is_registered('count')) {
session_register("count"); $count = 0; } else {
$count++; } print $count; ?>
Remember that if you
don't call session_start(), you never resume the session that you had
started before. In such a case, no session variables are registered, and
the session_is_registered() call will always return false, no matter what
you pass to it.
It's easy to forget the importance of the
session_start() function when you're used to using session_register()
because: "If session_start() was not called before this function is
called, an implicit call to session_start() with no parameters will be
made." (quoted from the session_register() documentation on this
site).
session_is_registered(), on the other hand, does not make
any implicit calls to session_start(). You have to do it yourself.
|
|
marius/at/ee\utt\ro
16-Aug-2002 04:16 |
|
my mistake:
session_start(); $love =
"mary"; session_register("love"); //love =
mary if... else... bla bla $love =
"ana"; session_register("love"); //love is not =
ana, as i expected. love = mary
to change $love from mary to
ana: $[HTTP]_SESSION[_VARS]["love"]="ana";
|
|
[email protected]
28-Aug-2002 10:44 |
|
I'm writing my first PHP application and I?ve tested the saving of the
session variables (I use PHP 4.0.6 on SuSE Linux). I've noticed the
following:
1. If register_globals is ON, the variables cannot
be seen in another page if you don't issue a session_register() after you
set the variables. For example the following code:
<?php
session_start (); $HTTP_SESSION_VARS[ 'testvar'] =
"variable transmission test"; $testvar =
'modified'; echo "<a href=
\"./secpage.php\">Link</a>"; ?>
won't display anything in a second page generated by the
code:
<?php session_start (); echo "Second
Page!"; echo " </br> "; if
(isset($HTTP_SESSION_VARS[ 'testvar'])) { echo
"HTTP_SESSION_VARS: " . $HTTP_SESSION_VARS[ 'testvar'];
}; echo " </br> "; if (isset($testvar))
{ echo "testvar: ". $testvar; }; ?>
After
I've added the session_register('testvar') line after setting the
variables, the following is displayed in the second
page:
HTTP_SESSION_VARS: modified testvar: modified
These
is strange because the manual specify not to use session_register if we
use $HTTP_SESSION_VARS.
2. If register_globals is off, you don't
need to use session_register('testvar') but in the second page
displays:
HTTP_SESSION_VARS: variable transmission
test
The conclusion is that if you want your code to work with
register_globals set either to On or OFF you must use session_register().
You must also use only $HTTP_SESSION_VARS to set the variable.
|
|
|
| |