Index: phpdoc/pl/functions/session.xml
+++ phpdoc/pl/functions/session.xml
Funkje obsługi sesjiSesje
Obsługa sesji w PHP ma na celu zapewnienie sposobu na zachowanie pewnych
danych w trakcie następujących po sobie wywołań strony. Pozwala to na
budowanie bardziej spersonalizowanych aplikacji i zwiększenie
atrakcyjności twojej strony internetowej.
Jeśli jesteś zaznajomiony z zarządzaniem sesją w PHPLIB, zauważysz że
pewnie koncepcje są podobne w obłudze sesji PHP.
Gość wchodzący na twoją stronę WWW otrzymuje unikalny identyfikator, tzw.
id sesji. Jest ono przechowywane albo jako ciasteczko po stronie
użytkownika lub propagowane w URL'u.
Obsługa sesji pozwala ci na rejestrowanie dowolnej ilości zmiennych, które
mają być przekazywane pomiędzy stronami. Kiedy gość wchodzi na twoją
strone, PHP automatycznie sprawdzi (jeśli session.auto_start jest ustawione
na 1) lub na twoje życzenie (jawnie przez wywołanie
session_start lub niejawnie przez wywołanie
session_register) czy specyficzne id sesji zostało
przypisane. Jeśli tak, poprzednio zachowane środowisko jest odtwarzane.
Wszystkie zarejestrowane zmienne są serializowane po wykonaniu całego kodu
strony. Zarejestrowane zmienne, które są niezdefiniowane, są zaznaczane
jako niezdefijiowane. Nie są one definiowane przez moduł sesji w
następujących po sobie wywołaniach, chyba że użytkownik zdefiniuje je
później.
Opcje konfiguracyjne track_vars i
register_globals
wpływają na to, jak zmienne sesyjne są przechowywane i odtwarzane.
Od PHP w wersji 4.0.3 opcja track_vars jest zawsze
włączona.
Jeśli włączona jest opcja track_vars a
register_globals
jest wyłączona, tylko pozycje należące do zmiennej asocjacyjnej
$HTTP_SESSION_VARS mogą być zarejestrowane jako zmienne sesyjne.
Odtworzone zmienne sesyjne będą dostępne tylko w zmiennej
$HTTP_SESSION_VARS.
Rejestracja zmiennej z włączoną opcją track_vars
<?php
session_register("count");
$HTTP_SESSION_VARS["count"]++;
?>
Jeśli włączona jest opcja register_globals,
wszystkie globalne zmienne mogą być zarejestrowane jako zmienne sesyjne a
zmienne sesyjne będą odtworzone do odpowiadających im zmiennych
globalnych.
Rejestracja zminnych z włączoną opcją register_globals
<?php
session_register("count");
$count++;
?>
Jeśli włączone są obie opcje, track_vars i
register_globals,
globalne zmienne i wpisy w $HTTP_SESSION_VARS będą referencjami do tej
samej wartości.
Istnieją dwie metody propagacji identyfikatora sesji:
Ciasteczka
Parametry URL'a
Moduł sesji obsługuje obie metody. Ciasteczka są metodą optymalną, ale
ponieważ nie są one pewne (klienci nie muszą ich akceptować), nie możęmy
na nich polegać. Druga metora wstawia identyfikatory sesji bezpośrednio do
URL'i.
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. Alternatively, you can use the constant
SID which is defined, if the client did not
send the appropriate cookie. SID is either of
the form session_name=session_id or is an empty
string.
The following example demonstrates how to register a variable, and
how to link correctly to another page using SID.
Counting the number of hits of a single user
<?php
session_register ("count");
$count++;
?>
Hello visitor, you have seen this page <?php echo $count; ?> times.<p>
<php?
# the <?=SID?> is necessary to preserve the session id
# in the case that the user has disabled cookies
?>
To continue, <A HREF="nextpage.php?<?=SID?>">click here</A>
The <?=SID?> is not necessary, if
--enable-trans-sid was used to compile PHP.
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.
To implement database storage, or any other storage method, you
will need to use session_set_save_handler to
create a set of user-level storage functions.
The session management system supports a number of configuration
options which you can place in your php.ini file. We will give a
short overview.
session.save_handler defines the name of the
handler which is used for storing and retrieving data
associated with a session. Defaults to
files.
session.save_path defines the argument which
is passed to the save handler. If you choose the default files
handler, this is the path where the files are created.
Defaults to /tmp.
If you leave this set to a world-readable directory, such as
/tmp (the default), other users on the
server may be able to hijack sessions by getting the list of
files in that directory.
session.name specifies the name of the
session which is used as cookie name. It should only contain
alphanumeric characters. Defaults to
PHPSESSID.
session.auto_start specifies whether the
session module starts a session automatically on request
startup. Defaults to 0 (disabled).
session.cookie_lifetime specifies the lifetime of
the cookie in seconds which is sent to the browser. The value 0
means "until the browser is closed." Defaults to
0.
session.serialize_handler defines the name
of the handler which is used to serialize/deserialize
data. Currently, a PHP internal format (name
php) and WDDX is supported (name
wddx). WDDX is only available, if PHP is
compiled with WDDX
support. Defaults to php.
session.gc_probability specifies the
probability that the gc (garbage collection) routine is started
on each request in percent. Defaults to 1.
session.gc_maxlifetime specifies the number
of seconds after which data will be seen as 'garbage' and
cleaned up.
session.referer_check contains the substring you
want to check each HTTP Referer for. If the Referer was sent by the
client and the substring was not found, the embedded session id will
be marked as invalid. Defaults to the empty string.
session.entropy_file gives a path to an
external resource (file) which will be used as an additional
entropy source in the session id creation process. Examples are
/dev/random or
/dev/urandom which are available on many
Unix systems.
session.entropy_length specifies the number
of bytes which will be read from the file specified
above. Defaults to 0 (disabled).
session.use_cookies specifies whether the
module will use cookies to store the session id on the client
side. Defaults to 1 (enabled).
session.cookie_path specifies path to set
in session_cookie. Defaults to /.
session.cookie_domain specifies domain to
set in session_cookie. Default is none at all.
session.cache_limiter specifies cache control
method to use for session pages (nocache/private/public).
Defaults to nocache.
session.cache_expire specifies time-to-live
for cached session pages in minutes, this has no effect for
nocache limiter. Defaults to 180.
session.use_trans_sid whether transient sid support
is enabled or not if enabled by compiling with
--enable-trans-sid.
Defaults to 1 (enabled).
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
Session handling was added in PHP 4.0.
session_startInitialize session dataDescriptionbool session_startsession_start creates a session (or resumes
the current one based on the session id being passed via a GET
variable or a cookie).
This function always returns &true;.
This function was added in PHP 4.0.
session_destroyDestroys all data registered to a sessionDescriptionbool session_destroysession_destroy destroys all of the data
associated with the current session.
This function returns &true; on success and
&false; on failure to destroy
the session data.
session_nameGet and/or set the current session nameDescriptionstring session_namestring
namesession_name returns the name of the current
session. If name is specified, the name of
the current session is changed to its value.
The session name references the session id in cookies and
URLs. It should contain only alphanumeric characters; it should
be short and descriptive (i.e. for users with enabled cookie
warnings). The session name is reset to the default value
stored in session.name at request startup
time. Thus, you need to call session_name
for every request (and before session_start
or session_register are called).
session_name examples
<?php
# set the session name to WebsiteID
$previous_name = session_name ("WebsiteID");
echo "The previous session name was $previous_name<p>";
?>
This function was added in PHP 4.0.
session_module_nameGet and/or set the current session moduleDescriptionstring session_module_namestring
modulesession_module_name returns the name of the
current session module. If module is
specified, that module will be used instead.
This function was added in PHP 4.0.
session_save_pathGet and/or set the current session save pathDescriptionstring session_save_pathstring
pathsession_save_path returns the path of the current
directory used to save session data. If path
is specified, the path to which data is saved will be changed.
On some operating systems, you may want to specify a path on a
filesystem that handles lots of small files efficiently. For
example, on Linux, reiserfs may provide better performance than
ext2fs.
This function was added in PHP 4.0.
session_idGet and/or set the current session idDescriptionstring session_idstring idsession_id returns the session id for the
current session. If id is specified, it
will replace the current session id.
The constant SID can also be used to
retrieve the current name and session id as a string suitable for
adding to URLs.
session_register
Register one or more variables with the current session
Descriptionbool session_registermixed namemixed
...session_register variable number of
arguments, any of which can be either a string holding the
variable name or an array consisting of such variable names or
other arrays. For each encountered variable name,
session_register registers the global
variable named by it with the current session.
This function returns &true; when the variable is successfully
registered with the session.
It is not currently possible to register resource variables in a
session. For example, you can not create a connection to a
database and store the connection id as a session variable and
expect the connection to still be valid the next time the
session is restored. PHP functions that return a resource are
identified by having a return type of
resource in their function definitions. A
list of functions that return resources are available in the
resource types appendix.
This function was added in PHP 4.0.
session_unregister
Unregister a variable from the current session
Descriptionbool session_unregisterstring namesession_unregister unregisters (forgets)
the global variable named name from the
current session.
This function returns &true; when the variable is successfully
unregistered from the session.
This function was added in PHP 4.0.
session_unset
Free all session variables
Descriptionvoid session_unset
The session_unset function free's all session variables
currently registered.
session_is_registered
Find out if a variable is registered in a session
Descriptionbool session_is_registeredstring namesession_is_registered returns &true; if there
is a variable with the name name
registered in the current session.
This function was added in PHP 4.0.
session_get_cookie_params
Get the session cookie parameters
Description
array session_get_cookie_params
The session_get_cookie_params function returns an
array with the current session cookie information, the array contains
the following items:
"lifetime" - The lifetime of the cookie.
"path" - The path where information is stored.
"domain" - The domain of the cookie.
session_set_cookie_params
Set the session cookie parameters
Descriptionvoid session_set_cookie_params
int lifetime
string path
string domain
Set cookie parameters defined in the php.ini file. The effect of this
function only lasts for the duration of the script.
session_decodeDecodes session data from a stringDescriptionbool session_decodestring datasession_decode decodes the session data in
data, setting variables stored in the
session.
This function was added in PHP 4.0.
session_encode
Encodes the current session data as a string
Descriptionstring session_encodesession_encode returns a string with the
contents of the current session encoded within.
This function was added in PHP 4.0.
session_set_save_handler
Sets user-level session storage functions
Descriptionvoid
session_set_save_handlerstring
openstring
closestring
readstring
writestring
destroystring
gcsession_set_save_handler sets the user-level
session storage functions which are used for storing and
retrieving data associated with a session. This is most useful
when a storage method other than those supplied by PHP sessions
is preferred. i.e. Storing the session data in a local database.
You must set the configuration option
session.save_handler to
user in your php.ini file for
session_set_save_handler to take effect.
The "write" handler is not executed until after the output
stream is closed. Thus, output from debugging statements in the
"write" handler will never be seen in the browser. If debugging
output is necessary, it is suggested that the debug output be
written to a file instead.
The following example provides file based session
storage similar to the PHP sessions default save handler
files. This example could easily be
extended to cover database storage using your favorite PHP
supported database engine.
session_set_save_handler example
<?php
function open ($save_path, $session_name) {
global $sess_save_path, $sess_session_name;
$sess_save_path = $save_path;
$sess_session_name = $session_name;
return(true);
}
function close() {
return(true);
}
function read ($id) {
global $sess_save_path, $sess_session_name;
$sess_file = "$sess_save_path/sess_$id";
if ($fp = <email protected>($sess_file, "r")) {
$sess_data = fread($fp, filesize($sess_file));
return($sess_data);
} else {
return("");
}
}
function write ($id, $sess_data) {
global $sess_save_path, $sess_session_name;
$sess_file = "$sess_save_path/sess_$id";
if ($fp = <email protected>($sess_file, "w")) {
return(fwrite($fp, $sess_data));
} else {
return(false);
}
}
function destroy ($id) {
global $sess_save_path, $sess_session_name;
$sess_file = "$sess_save_path/sess_$id";
return( <email protected>($sess_file));
}
/*********************************************
* WARNING - You will need to implement some *
* sort of garbage collection routine here. *
*********************************************/
function gc ($maxlifetime) {
return true;
}
session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");
session_start();
// proceed to use sessions normally
?>
session_cache_limiterGet and/or set the current cache limiterDescriptionstring session_cache_limiterstring
cache_limitersession_cache_limiter returns the name of the
current cache limiter. If cache_limiter is
specified, the name of the current cache limiter is changed to the
new value.
The cache limiter controls the cache control HTTP headers sent to the
client. These headers determine the rules by which the page content
may be cached. Setting the cache limiter to nocache,
for example, would disallow any client-side caching. A value of
public, however, would permit caching. It can also
be set to private, which is slightly more restrictive
than public.
The cache limiter is reset to the default value stored in
session.cache_limiter at request startup time. Thus,
you need to call session_cache_limiter for every
request (and before session_start is called).
session_cache_limiter examples
<?php
# set the cache limiter to 'private'
session_cache_limiter('private');
$cache_limiter = session_cache_limiter();
echo "The cache limiter is now set to $cache_limiter<p>";
?>
This function was added in PHP 4.0.3.
session_write_closeWrite session data and end sessionDescriptionvoid session_write_close
End the current session and store session data.
Session data is usually stored after your script terminated
without the need to call session_write_close, but as
session data is locked to prevent concurrent writes only one
script may operate on a session at any time. When using framesets
together with sessions you will experience the frames loading one
by one due to this locking. You can reduce the time needed to
load all the frames by ending the session as soon as all changes
to session variables are done.