Professional Documents
Culture Documents
Introduction
Session support in PHP consists of a way to preserve certain data across subsequent
accesses. This enables you to build more customized applications and increase the appeal
of your web site.
A visitor accessing your web site is assigned a unique id, the so-called session id. This is
either stored in a cookie on the user side or is propagated in the URL.
The session support allows you to register arbitrary numbers of variables to be preserved
across requests. When a visitor accesses your site, PHP will check automatically (if
session.auto_start is set to 1) or on your request (explicitly through session_start() or
implicitly through session_register()) whether a specific session id has been sent with the
request. If this is the case, the prior saved environment is recreated.
Caution
If you do turn on session.auto_start then you cannot put objects into your sessions since
the class definition has to be loaded before starting the session in order to recreate the
objects in your session.
All registered variables are serialized after the request finishes. Registered variables
which are undefined are marked as being not defined. On subsequent accesses, these are
not defined by the session module unless the user defines them later.
Warning
Some types of data can not be serialized thus stored in sessions. It includes resource
variables or objects with circular references (i.e. objects which passes a reference to itself
to another object).
Note: Please note when working with sessions that a record of a session is not created
until a variable has been registered using the session_register() function or by adding a
new key to the $_SESSION superglobal array. This holds true regardless of if a session
has been started using the session_start() function.
Assess the importance of the data carried by your sessions and deploy additional
protections -- this usually comes at a price, reduced convenience for the user. For
example, if you want to protect users from simple social engineering tactics, you need to
enable session.use_only_cookies. In that case, cookies must be enabled unconditionally
on the user side, or sessions will not work.
There are several ways to leak an existing session id to third parties. A leaked session id
enables the third party to access all resources which are associated with a specific id.
First, URLs carrying session ids. If you link to an external site, the URL including the
session id might be stored in the external site's referrer logs. Second, a more active
attacker might listen to your network traffic. If it is not encrypted, session ids will flow in
plain text over the network. The solution here is to implement SSL on your server and
make it mandatory for users.
Requirements
No external libraries are needed to build this extension.
Note: Optionally you can use shared memory allocation (mm), developed by Ralf S.
Engelschall, for session storage. You have to download mm and install it. This option is
not available for Windows platforms. Note that the session storage module for mm does
not guarantee that concurrent accesses to the same session are properly locked. It might
be more appropriate to use a shared memory based filesystem (such as tmpfs on
Solaris/Linux, or /dev/md on BSD) to store sessions in files, because they are properly
locked. Session data is stored in memory thus web server restart deletes it.
Installation
Session support is enabled in PHP by default. If you would not like to build your PHP
with session support, you should specify the --disable-session option to configure. To use
shared memory allocation (mm) for session storage configure PHP --with-mm[=DIR] .
The windows version of PHP has built in support for this extension. You do not need to
load any additional extension in order to use these functions.
Note: By default, all data related to a particular session will be stored in a file in the
directory specified by the session.save_path INI option. A file for each session (regardless
of if any data is associated with that session) will be created. This is due to the fact that a
session is opened (a file is created) but no data is even written to that file. Note that this
behavior is a side-effect of the limitations of working with the file system and it is
possible that a custom session handler (such as one which uses a database) does not keep
track of sessions which store no data.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
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 string
session.save_handler defines the name of the handler which is used for storing
and retrieving data associated with a session. Defaults to files. Note that
individual extensions may register their own save_handlers; registered handlers
can be obtained on a per-installation basis by referring to phpinfo(). See also
session_set_save_handler().
session.save_path string
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. See
also session_save_path().
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.
Note: Prior to PHP 4.3.6, Windows users had to change this variable in order to
use PHP's session functions. A valid path must be specified, e.g.: c:/temp.
session.name string
session.name specifies the name of the session which is used as cookie name. It
should only contain alphanumeric characters. Defaults to PHPSESSID. See also
session_name().
session.auto_start boolean
session.auto_start specifies whether the session module starts a session
automatically on request startup. Defaults to 0 (disabled).
session.serialize_handler string
session.serialize_handler defines the name of the handler which is used to
serialize/deserialize data. Currently, a PHP internal format (name php or
php_binary) and WDDX are supported (name wddx). WDDX is only available, if
PHP is compiled with WDDX support. Defaults to php.
session.gc_probability integer
session.gc_probability in conjunction with session.gc_divisor is used to manage
probability that the gc (garbage collection) routine is started. Defaults to 1. See
session.gc_divisor for details.
session.gc_divisor integer
session.gc_divisor coupled with session.gc_probability defines the probability
that the gc (garbage collection) process is started on every session initialization.
The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means
there is a 1% chance that the GC process starts on each request.
session.gc_divisor defaults to 100.
session.gc_maxlifetime integer
session.gc_maxlifetime specifies the number of seconds after which data will be
seen as 'garbage' and cleaned up. Garbage collection occurs during session start.
Note: If you are using the default file-based session handler, your filesystem must
keep track of access times (atime). Windows FAT does not so you will have to
come up with another way to handle garbage collecting your session if you are
stuck with a FAT filesystem or any other filesystem where atime tracking is not
available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So,
you won't have problems with filesystems where atime tracking is not available.
session.referer_check string
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 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 integer
session.entropy_length specifies the number of bytes which will be read from the
file specified above. Defaults to 0 (disabled).
session.use_cookies boolean
session.use_cookies specifies whether the module will use cookies to store the
session id on the client side. Defaults to 1 (enabled).
session.use_only_cookies boolean
session.use_only_cookies specifies whether the module will only use cookies to
store the session id on the client side. Enabling this setting prevents attacks
involved passing session ids in URLs. This setting was added in PHP 4.3.0.
Defaults to 1 (enabled) since PHP 6.0.
session.cookie_lifetime integer
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. See also session_get_cookie_params() and session_set_cookie_params().
Note: The expiration timestamp is set relative to the server time, which is not
necessarily the same as the time in the client's browser.
session.cookie_path string
session.cookie_path specifies path to set in session_cookie. Defaults to /. See also
session_get_cookie_params() and session_set_cookie_params().
session.cookie_domain string
session.cookie_domain specifies the domain to set in session_cookie. Default is
none at all meaning the host name of the server which generated the cookie
according to cookies specification. See also session_get_cookie_params() and
session_set_cookie_params().
session.cookie_secure boolean
session.cookie_secure specifies whether cookies should only be sent over secure
connections. Defaults to off. This setting was added in PHP 4.0.4. See also
session_get_cookie_params() and session_set_cookie_params().
session.cookie_httponly boolean
Marks the cookie as accessible only through the HTTP protocol. This means that
the cookie won't be accessible by scripting languages, such as JavaScript. This
setting can effectively help to reduce identity theft through XSS attacks (although
it is not supported by all browsers).
session.cache_limiter string
session.cache_limiter specifies cache control method to use for session pages
(none/nocache/private/private_no_expire/public). Defaults to nocache. See also
session_cache_limiter().
session.cache_expire integer
session.cache_expire specifies time-to-live for cached session pages in minutes,
this has no effect for nocache limiter. Defaults to 180. See also
session_cache_expire().
session.use_trans_sid boolean
session.use_trans_sid whether transparent sid support is enabled or not. Defaults
to 0 (disabled).
session.bug_compat_42 boolean
PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you
to initialize a session variable in the global scope, albeit register_globals is
disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if
session.bug_compat_warn is also enabled. This feature/bug can be disabled by
disabling this directive.
session.bug_compat_warn boolean
PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you
to initialize a session variable in the global scope, albeit register_globals is
disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling
both session.bug_compat_42 and session.bug_compat_warn.
session.hash_function mixed
session.hash_function allows you to specify the hash algorithm used to generate
the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits).
Since PHP 6.0.0 it is also possible to specify any of the algorithms provided by
the hash extension (if it is available), like sha512 or whirlpool. A complete list of
supported algorithms can be obtained with the hash_algos() function.
session.hash_bits_per_character integer
session.hash_bits_per_character allows you to define how many bits are stored in
each character when converting the binary hash data to something readable. The
possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").
Note: If you want HTML/XHTML strict conformity, remove the form entry and
use the <fieldset> tags around your form fields.
The track_vars and register_globals configuration settings influence how the session
variables get stored and restored.
Resource Types
This extension has no resource types defined.
Predefined Constants
The constants below are defined by this extension, and will only be available when the
extension has either been compiled into PHP or dynamically loaded at runtime.
SID (string)
Constant containing either the session name and session ID in the form of
"name=ID" or empty string if session ID was set in an appropriate session cookie.
Examples
Note: As of PHP 4.1.0, $_SESSION is available as a global variable just like $_POST,
$_GET, $_REQUEST and so on. Unlike $HTTP_SESSION_VARS, $_SESSION is always
global. Therefore, you do not need to use the global keyword for $_SESSION. Please
note that this documentation has been changed to use $_SESSION everywhere. You can
substitute $HTTP_SESSION_VARS for $_SESSION, if you prefer the former. Also note
that you must start your session using session_start() before use of $_SESSION becomes
available.
The keys in the $_SESSION associative array are subject to the same limitations as
regular variable names in PHP, i.e. they cannot start with a number and must start with a
letter or underscore. For more details see the section on variables in this manual.
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?>
Caution
Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the
registering of session variables through the $_SESSION superglobal.
Warning
You can't use references in session variables as there is no feasible way to restore a
reference to another variable.
Caution
Before PHP 4.3.0, if you are using $_SESSION and you have disabled register_globals,
don't use session_register(), session_is_registered() or session_unregister(). Disabling
register_globals is recommended for both security and performance reasons.
If register_globals is enabled, then the global variables and the $_SESSION entries will
automatically reference the same values which were registered in the prior session
instance. However, if the variable is registered by $_SESSION then the global variable is
available since the next request.
There is a defect in PHP 4.2.3 and earlier. If you register a new session variable by using
session_register(), the entry in the global scope and the $_SESSION entry will not
reference the same value until the next session_start(). I.e. a modification to the newly
registered global variable will not be reflected by the $_SESSION entry. This has been
corrected in PHP 4.3.0.
Cookies
URL parameter
The session module supports both methods. Cookies are optimal, but because they are not
always available, we also provide an alternative way. The second method embeds the
session id directly into URLs.
PHP is capable of transforming links transparently. Unless you are using PHP 4.2.0 or
later, you need to enable it manually when building PHP. Under Unix, pass --enable-
trans-sid to configure. If this build option and the run-time option session.use_trans_sid
are enabled, relative URIs will be changed to contain the session id automatically.
Alternatively, you can use the constant SID which is defined if the session started. If the
client did not send an appropriate session cookie, it has the form
session_name=session_id. Otherwise, it expands to an empty string. Thus, you can
embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link correctly
to another page using SID.
<?php
session_start();
if (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
?>
<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?>
times.
</p>
<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?
>">click
here</a>.
</p>
The htmlspecialchars() may be used when printing the SID in order to prevent XSS
related attacks.
Printing the SID, like shown above, is not necessary if --enable-trans-sid was used to
compile PHP.
Note: 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.
Table of Contents
session_cache_expire Return current cache expire
session_cache_limiter Get and/or set the current cache limiter
session_commit Alias of session_write_close
session_decode Decodes session data from a string
session_destroy Destroys all data registered to a session
session_encode Encodes the current session data as a string
session_get_cookie_params Get the session cookie parameters
session_id Get and/or set the current session id
session_is_registered Find out whether a global variable is registered in a
session
session_module_name Get and/or set the current session module
session_name Get and/or set the current session name
session_regenerate_id Update the current session id with a newly generated
one
session_register Register one or more global variables with the current session
session_save_path Get and/or set the current session save path
session_set_cookie_params Set the session cookie parameters
session_set_save_handler Sets user-level session storage functions
session_start Initialize session data
session_unregister Unregister a global variable from the current session
session_unset Free all session variables
session_write_close Write session data and end session
session_cache_expire session_pgsql_status
you can get the same result by using this much simplier function call:
<?php
session_start();
session_regenerate_id();
?>
at the top of the file.
anonymousleaf at gmail dot com
22-Feb-2008 07:41
You can secure your sessions by copying the session data and resetting
the ID. The simplest way to do this would be to reset the session, so
<?php
session_start(); // Start the session at the top of the file
$old_data = $_SESSION; // back up the data
session_destroy(); // Delete the session
session_start(); // We have another session now with a fresh ID
$_SESSION = $old_data; // Restore the session
unset($old_data); // Free space!
?>
ajmconsulting_dot_net
12-Jan-2008 02:26
Another way of handling the "www" versus non-"www" URL's:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourdomain.com$
RewriteRule ^(.*)$ http://yourdomain.com/$1 [R=301,L]
to:
yourdomain.com/anything
To reverse, e.g. add a www if it isn't present, change the 3rd line to:
if($HTTP_HOST == "myhost.net")
header('Location: http://www.myhost.net' . $PHP_SELF);
if($HTTP_HOST == "www.myhost.net")
header('Location: http://myhost.net' . $PHP_SELF);
Just throw that in a PHP file and include it at the top of all your PHP
pages that are accessed. This way, before sessions are even used in a
script, the access path is right. I think it should work out just fine.
Hope it helps anyone with similar issues.
Anonymous
18-Dec-2007 11:10
Hey people,
session.save_path = "c:\Windows\Temp"
Maybe this will serve as a starting point and save some time for some of
you out there who start from a fresh php.ini.
--Matthew
carl /a/ suchideas /o/ com
30-Sep-2007 09:45
Another gotcha to add to this list is that using a relative
session.save_path is a VERY BAD idea.
You can just about pull it off, if you're very careful, but note two
related points:
<?php ini_set("session.save_path",dirname(__FILE__)."/relative_path"); ?
>
(or equivalent) in a file which you know is always in the same place
relative to the file.
You can't just call a session variable. All you get is the Session ID.
With the Session ID you can track the user.
But there are no Session Variables that you can create that work like
ASP's Session("VariableName").
nn162077php at smallcue dot com
11-Aug-2007 04:20
Bruno's posting of mod_files works for default (16) or 32, but it
doesn't work for 64. The following isn't great code since I'm not a
great shell coder, but it does work better. It replaces the middle
section of Bruno's script
hash_chars="0 1 2 3 4 5 6 7 8 9 a b c d e f"
if test "$3" ; then
if test "$3" -eq "32"; then
hash_chars="$hash_chars g h i j k l m n o p q r s t u v"
fi
if test "$3" -eq "64"; then
hash_chars="$hash_chars g h i j k l m n o p q r s t u v"
hash_chars="$hash_chars w x y z A B C D E F G H I J K L M N O P Q R
S T U V W X Y Z - ,"
fi
fi
1) use fieldsets around *all* input fields (for xhtml 1.0+) to pass
validation
2) then, before session_start() change the url_rewriter.tags list of
tags to drop form and add fieldset:
ini_set("url_rewriter.tags",
"a=href,area=href,frame=src,fieldset=");
session_start();
You can also set url_rewriter.tags anywhere, (see appendix for php.ini)
legolas558 d0t users dot sf dot net
01-May-2007 08:45
To clear out a possible doubt of other readers which have read this part
of "Eric dot Deplagne at nerim dot net" note:
--------
In fact, two other variables (at least) play a role in session duration,
and will explain that the session might last more than expected. The gc
erasing your data is a probabilistic thing. Each time a session is
opened, the probability the gc is started is
session.gc_probability/session.gc_divisor. session.gc_probability
defaults to 1 and session.gc_divisor defaults to 100, which makes a 1%
probability.
This is to have sessions long enough. I'm unsure about having sessions
lasting exactly the time we want them to.
--------
The probabilistic fact is that old sessions will not be erased if the
garbage collector is not run frenquently enough, but anyway it is your
choice to have a higher or lower "session.gc_probability" on
"session.gc_divisor" ratio.
So, talking from the server side point of view, a session can last more
than the specified amount of time but not less. And if the client
respects the cookies duration (in case of cookie-based sessions) those
invalid sessions will not last more than expected.
You finally might want to add a timestamp inside the session and
validate its age through it to radically solve the problem, if
necessary. Example:
<?php
session_start();
if (!isset($_SESSION['generated']))
$_SESSION['generated'] = time();
else { // if the session is not allowed to live more, regenerate it
if (time() - $_SESSION['generated'] >
ini_get('session.gc_maxlifetime'))
$_SESSION = array('generated' => time());
}
?>
g_s_b
27-Apr-2007 08:37
If you try to use your own session handling functions (eg. for saving
session data to DB) make sure session.auto_start directive is 0.
The manual warns about not being able to put objects in your sessions
with auto_start=1: I guess that for the same reason your customized
handling functions are ignored is sessions start automatically.
May you have noticed when you open your website in two or more tabs in
Firefox, Opera, IE 7.0 or use 'Control+N' in IE 6.0 to open a new
window, it is using the same cookie or is passing the same session id,
so the another tab is just a copy of the previous tab. What you do in
one will affect the another and vice-versa. Even if you open Firefox
again, it will use the same cookie of the previous session. But that is
not what you need mostly of time, specially when you want to copy
information from one place to another in your web application. This
occurs because the default session name is "PHPSESSID" and all tabs will
use it. There is a workaround and it rely only on changing the session's
name.
Put these lines in the top of your main script (the script that call the
subscripts) or on top of each script you have:
if(version_compare(phpversion(),'4.3.0')>=0) {
if(!ereg('^SESS[0-9]+$',$_REQUEST['SESSION_NAME'])) {
$_REQUEST['SESSION_NAME']='SESS'.uniqid('');
}
output_add_rewrite_var('SESSION_NAME',$_REQUEST['SESSION_NAME']);
session_name($_REQUEST['SESSION_NAME']);
}
How it works:
header('location: script.php?'.session_name().'='.session_id()
. '&SESSION_NAME='.session_name());
So, every link, form, header() and Javascript code will forward the
SESSION_NAME value to the next script and it will know which is the
session it must use. If none is given, it will generate a new one (and
so, create a new session to a new tab).
May you are asking why not use a cookie to pass the SESSION_NAME along
with the session id instead. Well, the problem with cookie is that all
tabs will share the same cookie to do it, and the sessions will mix
anyway. Cookies will work partially if you set them in different paths
and each cookie will be available in their own directories. But this
will not make sessions in each tab completly separated from each other.
Passing the session name through URL via GET and POST is the best way, I
think.
Marcin Wiazowski
03-Apr-2007 01:11
'session.cookie_domain' should be set to empty string for all local
domain names, not only for 'localhost' (but should not be empty for
local IP addresses):
<?php
ini_set('session.cookie_domain', (strpos($_SERVER['HTTP_HOST'],'.') !==
false) ? $_SERVER['HTTP_HOST'] : '');
?>
gordon_e_rouse at yahoo dot com dot au
28-Mar-2007 08:06
Multi-site security risk!
Suppose you use session security to determine login status, and you have
several such sites on the webserver which essentially assign a session
token to determine your login status. A common occurence for
webdeveloping companies that have a standard system or package, and are
not using a high security setup. (ie all sites share the same session
path directory)
PHP sends the browser a cookie and that cookie should only be valid for
the site it was retrieved from, but only the browser determines this,
the server does not record the path or domain with the session cookie,
so technically you could modify the browsers cookie jar to send the same
cookie request for a different domain or path than what was originally
meant.
This means that if the same session variables are used to determine a
logon status on different sites on this server, then the user can access
all these sites with the one session id.
<?
$_SESSION['x'] = "foo";
$x = $_SESSION['x'];
echo $x; // "foo"
$_SESSION['x'] = "bar";
echo $x; // "bar";
?>
<?
$_SESSION['x'] = "foo";
$x = $_SESSION['x'];
$y = $x;
echo $y; // "foo"
$_SESSION['x'] = "bar";
echo $y; // "foo";
?>
Parikesit
09-Feb-2007 10:26
localhost problem
-----------------
When using localhost and session.cookies not work, simply remove domain
from session.cookie_domain.
$cookie_path = 'my_path';
$cookie_domain = 'localhost'; //or any valid domain
init_session_cookies($cookie_path, $cookie_domain);
Best,
Parikesit (zae_lokamaya #at# yahoo #dot# co #dot# uk)
Jim Rogers at mail dot com
30-Jan-2007 08:57
url_rewriter.tags = "a=href,area=href,frame=src,fieldset="
Modifying url_rewriter.tags to the above line in the php.ini file gave
me mixed results, including some pages adding the sessionid after BOTH
the form tag and the fieldset tag.
Then I noticed the comment at the top of the php.ini file: "If you
modify the file, you must copy it to all subdirectories that contain
php." This has to do with the search order php uses to find the php.ini
file. PHP looks in the current working directory first.
Works.
Dave Matlock
29-Jan-2007 02:35
In reference to the IE6 issue that results in loss of session data after
a page refresh, I found a solution. In my case, the host that was
experiencing the issue contained an underscore (host_dev). Apparently
underscores are not valid in host names and IE is the only browser that
seems to care. I removed the underscore and all is well. I found this
information here:
http://us2.php.net/manual/en/function.setcookie.php#67262
Stephen
02-Jan-2007 04:47
jmoore at sober dot dk wrote: "Note: Changing sessions to use a
directory other than /tmp will be harder to find, but no more secure."
But you should only type mod_files.sh (or whatever the name of your
script file is) once, not twice. It doesn't need its own name as an
argument.
Also - make sure you don't make the silly mistake I did of naming your
script file "script" and then trying to call it with the argument:
script /tmp/session 3 32
<?
$setting = $_REQUEST['setting'];
if (!empty($setting))
$_SESSION['setting'] = $setting;
?>
Your generated ids arent safe, they are guessable because depending only
on guessable vars. You must add a random var to your id (ie in
md5( ... ) )
robin at amiance dot com
26-Nov-2006 10:19
If you want the simplest way there is to log a session out after 30
minutes (or any other period of inactivity) simply add a second line
after session_start(), like this:
session_start();
setcookie("PHPSESSID",$_COOKIE['PHPSESSID'],time()+1800);
Where 1800 is the time in seconds before the session should expire.
PHPSESSID is the default session ID. This way, every time a user loads a
page they get their session extended.
klenwell at gmail dot com
05-Oct-2006 05:39
In response to marou at marou dot com responding to fondman at hotmail
dot com regarding local variables overwriting SESSION variables:
http://www.nyphp.org/phundamentals/ini.php
http://tinyurl.com/o6p7y
wings at 25th dot com
05-Oct-2006 06:59
Jestin's Session class is a nice alternative, but I had trouble with
it. The results of the filesize() function are cached. I ended up
having to put a call to clearstatcache() at the head of
Session::_getdata(); Otherwise, your session data gets truncated.
steffen at steffen-ille dot de
13-Sep-2006 05:02
old problem was:
internet explorer has security settings which reject your php session
cookie within different framesets (third party cookies). one approach to
handle this was to pass the session id to the other frames in the url.
the www says, this is a little bit unsafe...
another trick to handle this is, to trick the explorer with the php
header funktion. as described in the microsoft knowledgebase
article http://support.microsoft.com/kb/323752/EN-US/
you simply add a header at the top of your scripts _bevore_ the
session_start() is called:
The issue was even harder to figure out, because the page with the wrong
session ID was NOT creating a second cookie. The only cookie was the
one with the proper ID, but the broken page did not use this cookie
(where then, did it get this ID from?).
To fix the problem, I simply removed the forward-slash from the GET data
(base64_encoding works nicely).
I imagine this is an issue with my browser parsing the url, but I tried
both Opera and Firefox (IE doesn't load anymore :/) and both browsers
showed the same problem.
if the main script (which outputs the html) doesn't have a value in it's
session which says that a session is running successfully a different
value is saved in the session and an image is included in the html which
checks wether the session-check value is set or not.
If it's set the image-script sets a confirming value which will verify
the session to be running correctly and output a transparent 1*1px gif.
If the value is not set the image outputs an advising image which tells
to allow cookies.
You can also wrap the image with a link who refers the user to a page
addressing the cookie issue. If the 1px trans is generated the user will
hardly find the link, but if the error-image is generated he will surely
be able to click it.
pros:
- works
- no rerouting, you can see the result on the first page opened by the
user
- no javascript
cons:
- bad accessebility (if you give the image an alt-text any blind user
will read it at least on the first call, but you cold also write this
into the alt text... so maybe there are no cons)
The first request to your site will not contain cookie data from the
user. Some developers do a little trick on the server at this point to
redirect the user to the same or different page and in so doing
endeavour to deliver a cookie so that it can then be determined if this
was successful on the second request. It has the advantage of letting
the no-cookie user know at the on-set if there is a problem. Of course
this adds an overhead of time and server resources. It also might impare
your site's position with popular search engines.
So, since many sites will work to a point without sessions working (i.e.
scatterings of static links and basic searches), I allow the user to
load the first page and then perform the cookie check upon the user's
subsequent request. If the cookie canot be found I place advice text
accordingly
function cookie_check() {
if (!isset($_COOKIE['PHPSESSID'])) {
return false;
} else {
return true;
}
if (!cookie_check()) {
echo "This site uses cookies, dah dah dah...";
}
I have looked fairly extensively for information on this issue but there
isn't a great deal about. So, if anyone out there has more experience of
this...
entropicchild
23-Aug-2006 09:09
I just went looking through the /tmp dir on a shared hosting server, and
noticed all the php sessions stored there (bad idea for shared hosting).
I noticed that some of these people/scripts are storing plain-text
passwords in their sessions (another very bad idea). Here's a hint
people: do not store ANYTHING that may present a security risk in the
session data! This includes, passwords, creditcard information, etc.
It is best, under ALL circumstances that a dir other than /tmp be used
for session data. Btw, whomever it was that said it was no more secure
to use a diff dir was wrong. The /tmp dir is a globally
readable/writable dir.
If you are using shared hosting, then you better be sure your session
data is being saved within your home dir and NOT web-accessible. If you
are a shared hosting sysadmin, you should be doing this for your users
automatically... as well as any other tmp files (file uploads, etc...).
http://mike.eire.ca/
09-Aug-2006 03:08
It should be noted that PHP makes the decision about whether SID is
empty based on the HTTP request. Specifically, if there is no cookie
sent with the GET or POST request, SID is populated when the session is
initiated.
What does this mean? If you want your site to support clients who have
cookies disabled, your links will have PHPSESSID appended to them on the
page where the session is created.
Here we are. As you can read in the example it should be a path you
control (and your web server can write), with no access via URL.
In fact, two other variables (at least) play a role in session duration,
and will explain that the session might last more than expected. The gc
erasing your data is a probabilistic thing. Each time a session is
opened, the probability the gc is started is
session.gc_probability/session.gc_divisor. session.gc_probability
defaults to 1 and session.gc_divisor defaults to 100, which makes a 1%
probability.
This is to have sessions long enough. I'm unsure about having sessions
lasting exactly the time we want them to.
rehevkor5 at fastmail dot fm
25-May-2006 11:34
If you have a value specified for session.referer_check you may run into
difficulty when someone accesses your site and attempts to log in with a
mis-capitalized URL. The logon will fail because any calls to
session_start() will result in the existing session being trashed and a
new one being created. This becomes a bigger problem when the logon is
followed by a header("Location: ...") redirect, because the
session_start() at the top of the page will fail.
ini_set('session.referer_check', 'www.yourdomain.edu/ltr/');
ini_set('session.use_only_cookies', 1);
session_name('yourapp'.str_replace('.', '', $_SERVER['REMOTE_ADDR']));
session_start();
if($_GET['badreferer'])
echo 'You tried accessing the site with a bad URL. Try logging on
again.';
if(isUserAuthed($name, $pass))
{
$old_sessid = session_id(); //save current session id so we can
delete it later
if( !session_regenerate_id() ) //get a new session id (must do this
before destroying the old session)
die("Couldn't regenerate your session id.");
session_id($old_sessid);
unset($old_sessid);
session_destroy(); //destroy the session they got before they logged
in
session_id($new_sessid);
session_start(); //start the new session
if(session_id() != $new_sessid)
{
/*If this is true, then the session_start() failed to work
properly. If session_start() failed to work properly, the most likely
cause is that the referer url is different from that set in fuxebox.ini
on session.referer_check. The most common cause of this is URL
capitalization problems. Therefore, we relocate them to the proper URL,
and set a flag to display an error because we can't use pushError() if
the session isn't valid. */
$good_url = ini_get('session.referer_check');
header('Location: http://'.$good_url.'?badreferer=1');
exit;
} else {
unset($new_sessid);
//Set session variables here
$_SESSION['isloggedin'] = 1;
}
rajasekhar_s7 at yahoo dot co dot in
19-May-2006 04:07
POST the variable can give the page Expire Warnig when you press the
BACK button.
Solution: Put this code on the page top.
<? session.cashe.limiter(private, must-revalidate) ?>
php AT coryforsyth [removeme] d0t com
08-May-2006 07:14
I just finished a marathon debugging session with sessions, and I wanted
to share what I learned with the rest of the PHP community because this
has been a problem I've battled on several projects before finally
solving it today.
$auth = false;
if (isset($_SESSION['user_id'])) {
$user = new User($_SESSION['user_id']);
$auth = true;
else {
$login = $_REQUEST['login'];
$password = $_REQUEST['password'];
$login = clean($login);
$password = clean($password);
// clean() is my own function to escape quotes and so on
$user = checkLogin($login,$password);
if (!is_null($user)) {
$auth = true;
}
}
if (!$auth) {
die("you must log in.");
}
What I realized was that the URL was changing from www.coryforsyth.com
to coryforsyth.com. When the presence of the WWW changed, PHP thought
it was a different session and created an empty one that caused my
script to log me out. If I went to the location bar of my browser and
added/removed the WWW (to the way it had been before), all was well and
I was still logged in.
An incredibly thorny problem. I hope this post helps someone else fix
it, or even better prevent it. I changed my hosting preferences to
automatically add a WWW to my domain if it wasn't typed that way.
thanks,
Cory Forsyth
brady at volchok dot com
17-Apr-2006 12:15
Session locking (concurrency) notes:
The idea is that if your session code <b>mostly</b> reads from sessions,
and rarely writes to them, then you can allow concurrent access. To
prevent completely corrupted session data, we will lock the session's
backing store (tmp files usually) while we write to them. This means the
session is only locked for the brief instant that we are writing to the
backing store. However, this means that if you have two pages loading
simultaneously, and both modify the session, the <i>Last One Wins</i>.
Whichever one loads first will get its data overwritten by the one that
loads second. If this is okay with you, you may continue - otherwise,
use the session_write_close method, above.
If you have complicated bits of code that depend on some state in the
session, and some state in a database or text file, or something else -
again, you may not want to use this method. When you have two
simultaneous pages running, you might find that one page runs halfway
through, modifying your text file, then the second one runs all the way
through, further modifying your text file, then the first one finishes -
and your data might be mangled, or completely lost.
<?
function write($id, $sess_data)
{
global $sess_save_path, $sess_session_name;
$sess_file = "$sess_save_path/sess_$id";
if ($fp = @fopen($sess_file, "w")) {
flock($fp,LOCK_EX);
$results=fwrite($fp, $sess_data);
flock($fp,LOCK_UN);
return($results);
} else {
return(false);
}
}
?>
You will probably also want to add a GC (Garbage Collection) method for
the sessions, as well.
And of course, take this advice with a grain of salt - We currently have
it running on our testing server, and it seems to work OK there, but
people have reported terrible problems with the Shared Memory session
handler, and this method may be as unsafe as that.
You can also consider implementing your own locks for scary concurrency-
sensitive bits of your code.
marcosdsanchez {a t} gmail [_dot_] com
07-Apr-2006 07:52
********************WARNING***********************
[IP NUMBER]/example.php
Took me a lot of time to find out why my PHP sessions worked perfectly
in Firefox and Opera but they didn't work in internet explorer
***************************************************
Cosmo
01-Apr-2006 04:47
Fairly new to PHP, I've been looking to alter session timeouts on a
shared host where I don't have direct access to configure php.ini.
There doesn't appear to be any easy way to find out how to do this in
this manual (nor from a quick web search).
(on the first pass of the file, there is no session file - that's
established only when the script ends for the first time. Keep
reloading to test).
Comments welcome.
<?php
ini_set('session.gc_maxlifetime',30);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
session_start();
$_SESSION['guid'] = $guid;
$_SESSION['userdata'] = $response;
session_write_close();
a l bell at hutchison dot com dot au
28-Feb-2006 03:17
Please Note;
You can lose the session however if the the page contains a reference to
<img src=""> with name and id references (which may be used if the image
is referencing a dynamic image, called by javascript) This seems to
casue IE6 to refresh the page session id and hence loose the session.
This took hours for me to diagnose when users were getting unexpectedly
logged out of my site due to this "" in the img src.
kintar at infinities-within dot net
28-Feb-2006 09:10
Important note that it just took me the better part of two hours to
figure out: Even if you're using session_write_close(), calling exit
after a redirect will eat your session variables. I had the following:
Source of register.php:
<?PHP
if ($result)
{
redirect('success.php');
}
else
{
redirect('failure.php');
}
exit;
?>
/bonks self
phpkloss at wholewheatradio dot org
22-Feb-2006 12:57
If you're having trouble with unset($_SESSION[$something]) working,
here's what I discovered (Win2K/PHP 5.x.x). Assume you want to step
through $_SESSION and delete (i.e. unset) certain elements. So,
What I found was that although the $_SESSION elements were deleted in
memory, the actual session file was not being written out with the
changes (even after using session_write_close). What fixed it for me
was to COPY $_SESSION INTO A DUMMY ARRAY, THEN STEP THROUGH THAT DUMMY
ARRAY TO FIGURE OUT WHICH ELEMENTS OF THE REAL $_SESSION TO DELETE.
I.e.
foreach($_SESSION as $key=>$value) {
$dummy[$key]=$value; // copy to a dummy array
}
"Be warned, when working with tab-based browsers like Opera and Firefox,
sessions are preserved across tabs....IE deals with sessions just fine.
There is probably some way to adjust the settings in Firefox or Opera,
but that is not the default, and will affect most users."
In fact, the way sessions are managed among different browsers is not
all that different among MSIE and Opera and Firefox. You will find that
MSIE sessions can be maintained across browser windows, just like in FF
or Opera. However the difference that djohnson noted is because of the
way MSIE windows are created vs FF and Opera.
If you choose, in MSIE, "File->New Window", you will find that PHP
sessions are preserved from browser window to browser window.
If, OTOH, you start a new window of MSIE using the start menu or desktop
icon, a new instance of MSIE, with a new process ID, is started. *This*
instance does not have anything to do with any other previously existing
MSIE instances, and, thus, PHP sessions started in this new MSIE process
are distinct from PHP sessions in existing MSIE instances.
[code]
//http://php.net/manual/en/ref.session.php
session.gc_probability ... Defaults to 1.
session.gc_divisor .... session.gc_divisor defaults to 100.
[/code]
session.gc_probability = 1
session.gc_divisor = 1000
[/code]
Moral:your local php.ini may differ from what the manual provides.
jerry dot walsh at gmail dot com
24-Jan-2006 06:56
If you're using sharedance to distributed php sessions across a group of
machines beware of the following:
When i did this my requests per second jumped from 55 to 389 requests
per second!
darkelf79 at gmail dot com
20-Jan-2006 03:00
If you set the session_id through the calling URL, it *will not* set the
session cookie in 4.4.2.
For example:
www.example.com/?PHPSESSID=foo
This will set the session id to 'foo' but it won't actually set the
session cookie. The last known version I'm aware of is 4.3.3 where it
will set the cookie.
This doesn't appear to be definitively mentioned in here anywhere. But
according to the devs, it's not a bug. Hopefully this knowledge will
help you out if you're experiencing the same problem.
royappa at spiralfx dot com
16-Jan-2006 01:19
This is just to note that I was able to fix my problems due to the many
helpful comments here.
I believe what was happening is that the browser was not saving a local
copy of the file due to the "no-store" directive, when the user clicks
"Open" directly.
Thanks for all the help. I just want to add also that the following web
page was of great help to see the actual HTTP headers being sent by the
web app: http://www.rexswain.com/httpview.html
Much easier than doing telnet to port 80! Hope this helps other also.
Andrew Royappa
Ravi Chotalia
26-Dec-2005 07:12
In answer to..
-PHP SESSIONS NOT WORKING in with windows---
...solution on the session cookie path.
I am running Apache 2 and PHP 4.4.0 on a Windows XP SP2.
...
----------------------------------
Just an FYI.
jazfresh at hotmail dot com
19-Dec-2005 06:55
The vanilla implementation of session will blindly spew back the value
of the session_id that the user sends it after URL decoding it. This can
be used as an attack vector, by including strings like "%0D%0ALocation:
%20http://someothersite.com/%0D%0A" in the cookie. Never trust user
input, always cleanse it. If you only expect alphanumerics in the
session hash, reject any session_id that doesn't contain it.
<?php
if(!preg_match('#^[[:alnum:]]+$#', $_COOKIE['session_id'])) {
unset($_COOKIE['session_id']);
}
session_start();
?>
bgshea at gmail dot com
04-Dec-2005 01:18
to johnlonely at gmail dot com
i.e. www.example.dom/mywepage/
if cookie_path="/mywebpage"
then
www.example.dom/someonespage/
will not have access to them. I use this parameter without problems.
I'm not saying that this will make cookies secure, but certainly others
of www.example.dom will not have access to them.
This is better for servers that use the /~user/ user aliasing.
djhoma at gmail dot com
26-Nov-2005 03:39
As the reference mentions the value of the register_globals variable can
cause some problem if you use sessions for verification.
If GET variables are registered as global and you check whether the user
is already logged in like this:
<?php
if ($_REQUEST['password'] == "right_password") {
$password = true;
session_register('password');
}
//...later on:
if ($password) {
//secure content
}
?>
Notice, that if you guess the name of the verification variable and pass
it through the URL (index.php?password=true) and the register_globals is
true then a script like this lets you in.
I know this is a stupid mistake, but maybe I am not the only one who
made it...
So after you registered the $password var, you should check the login
with session_is_registered() function:
<?php
if (session_is_registered('password')) {
//secure content
}
?>
This function cannot be fooled by GET or POST variables...
I just noticed that it's possible to access the same session through
multiple apache virtual hosts.
So keep this in mind when using sessions for anything sensitive, and
make sure to encrypt the data (using the mcrypt functions for example,
when available).
Lachlan Hunt
10-Nov-2005 06:10
> Note: The arg_separator.output php.ini directive allows to customize
the argument seperator. For full XHTML conformance, specify & there.
arg_separator.output = "&"
arg_separator.output = ";"
http://www.w3.org/QA/2005/04/php-session
webmaster at vampirerave dot com
06-Nov-2005 11:27
If you want to receive the functionality of session.use_only_cookies but
are using a PHP version prior to 4.3.0, here's an easy way:
if (isset($_GET['PHPSESSID'])) {
exit;
}
This assumes:
session.name = PHPSESSID
Is set in /etc/php.ini
christopher dot klein at ecw dot de
23-Oct-2005 11:26
If you have trouble with Internet Explorer 6 and non-working sessions
(all session-data is lost after clicking on a link), please look user-
hints for setcookie().
You have to add the following line after session_start() to get sessions
working:
<?php
// Initalize session
session_start();
// Send modified header
header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
?>
lassial at hotmail dot com
23-Oct-2005 07:54
If you would like to ensure your sessions with referer checking you must
use iniset() regularly, as
so there is no way PHP can automatically know which URL you are
expecting, e.g. it does not assume SCRIPT_NAME or anything else.
[Session]
session.cookie_path = /
<?php
?>
Had the same problem that the cookies are saved, in my case att c:\\tmp,
but not recognized at reload of the page. The session.save_path must
also be set to blank.
The cookies are stored in c:\\windows\\temp.
So if You do not have activated the garbage collector You can find them
there for cleanup and error solving.
php at stevegiller dot co dot uk
07-Sep-2005 02:13
If you want prevent people directly setting, for example, a logged_in
session variable to bypass your checks using the url?logged_in=true
system, a quick trick is to try the line
I havent tried many things but I think maybe it is because windows needs
backslashes (\) instead of forward slashes (/), and if you just leave it
blank, it turns out ok.
artistan at cableone dot net
08-Aug-2005 10:29
I rewrote adodb's session management class to work across servers with
database managed sessions. Take a look at
http://phplens.com/lens/lensforum/msgs.php?id=13428
Christian Boltz <php-manual at cboltz dot de>
28-Jul-2005 04:33
Another note about session.bug_compat_42 and bug_compat_warn.
<?php
session_start();
$_SESSION['var'] = NULL;
$var = "foo";
?>
You'll get this warning if $_SESSION['var'] contains NULL and you assign
The following code will generate the error that I speak of, and will not
successfully generate the new session id, of course like I said above,
this only accours on PHP 5 & 5.0.4 under the Windows Environment.
<?php
define("_PATH_TMP", "./tmp");
ini_set('session.save_path', _PATH_TMP);
session_start();
$_SESSION['sid']['obsolete'] = session_id();
session_regenerate_id();
$_SESSION['sid']['replaced'] = session_id();
print_r($_SESSION);
?>
(I know that PHP may use defined constants that include '_' characters
at the beggining, if it has not already, but I am taking that chance
atm...)
This can simply be resolved by using the following code:
<?php
define("_PATH_TMP", dirname($_SERVER['SCRIPT_FILENAME']) . "/tmp");
ini_set('session.save_path', _PATH_TMP);
session_start();
$_SESSION['sid']['obsolete'] = session_id();
session_regenerate_id();
$_SESSION['sid']['replaced'] = session_id();
print_r($_SESSION);
?>
As you can see it uses the uses the servers environment to assurtain the
exact location to the script, then locates the next root directory of
it, and then allows you to define the tmp directory.
* Of course, you dont need to use a tmp directory, and this issue only
occurse when using subdirectorys, I found that the following works just
aswell, but this did not fit my needs!
<?php
define("_PATH_TMP", "./");
ini_set('session.save_path', _PATH_TMP);
session_start();
$_SESSION['sid']['obsolete'] = session_id();
session_regenerate_id();
$_SESSION['sid']['replaced'] = session_id();
print_r($_SESSION);
?>
jentulman at NOSPAM dot jentulman dot co dot uk
12-Jul-2005 01:40
Here's one for the 'session disapearing after a rediredt problem'. It's
nice and simple but drove me mad for a couple of hours.
I was getting reports of users logging in apparently successfully but
not actually being logged in and couldn't replicate it myself.
I had a configuration file called at the begining of my script setting
defines for physical and url paths, and users with the problem were
coming in on a domain alias so of course the login went fine, but then
they were redirected to a different domain and the cookie was pointless.
Not very technical I know but maybe it'll stop someone having to
headbang like I did.
gholyoak at courtdean dot com
22-Jun-2005 08:09
Problems with IE and Content Advisor.
It maybe obvious to some, but as its taken me over a week to sort this
out, I will post it here.
I have generated a 'pics-label' and added to the META tags on every page
and this appears to make IE happy.
HTH,
R. Rajesh Jeba Anbiah
nigelf at esp dot co dot uk
16-Jun-2005 04:52
Session data is not available to an object's __destruct method as
sessions are closed before the object is 'destroyed'.
Richard [at] postamble [dot] [co] [uk]
13-Jun-2005 07:44
Having to use transparent on a system where trans_sid was not compiled,
I came up with the folowing ob_start handler:
<?php
function ob_sid_rewrite($buffer){
$replacements = array(
'/<\s*(a|link|script)\s[^>]*(href|src)\s*=\s*"([^"]*)"/',
'/<\s*(a|link|script)\s[^>]*(href|src)\s*=\s*\'([^\'<>]*)\'/',
);
$buffer = preg_replace('/<form\s[^>]*>/',
'\0<input type="hidden" name="' . session_name() . '" value="' .
session_id() . '"/>', $buffer);
return $buffer;
}
function pa_sid_rewriter($matches){
$buf = $matches[0];
$url = $matches[3];
$url_orig=$url;
if ($url[0]=='/' || $url[0]=='#' || preg_match('/^[A-Za-z0-9]*:/',
$url))
return $buf;
$ses_name = session_name();
if (strstr($url, "$session_name="))
return $buf;
$p = strpos($url, "#");
$ref = false;
if($p){
$ref = substr($url, $p);
$url = substr($url, 0, $p);
}
if (strlen($url)==0)
return $buf;
if (!strstr($url, "?"))
$url.="?";
else
$url.="&";
$url.=session_name() ."=".session_id();
if($ref)
$url.=$ret;
return str_replace($url_orig, $url, $buf);
}
?>
You can start the rewrite by doing the folowing at the start of the
script:
<?php
function pa_set_trans_sid(){
if ( defined('SID') ){ // use trans sid as its available
ini_set("session.use_cookies", "0");
ini_set("session.use_trans_sid", "true");
ini_set("url_rewriter.tags",
"a=href,area=href,script=src,link=href,"
. "frame=src,input=src,form=fakeentry");
}else{
ob_start('ob_sid_rewrite');
}
}
?>
webmaster at paginadespud dot com
28-Mar-2005 09:10
hi all,
i've been troubles with sessions at my production server for weeks and
today i've noticed the problem.
If you use /tmp as php sessions file dir, on a procuction server, system
garbage will delete randomly files when a certain number os files are
stored at tmp, so some sessions are deleted within 1 seconds, like my
case.
Solution? use another dir for php sessions file, and be careful of using
a shell script for your own garbage collection, called from cron, with
this line:
cd /path/to/sessions; find -cmin +24 | xargs rm
Spud.
anders
02-Mar-2005 06:15
It's true that session variables are stored on-server, but for the
server to know which session the user is using, a cookie is used. If you
check your cookie cache, you'd see that the only session-related
information you find in your cookie is a session id, no matter how much
information you store in $_SESSION.
trev at beammeupnowplease dot com
03-Jan-2005 08:09
You can't turn off session.use_trans_sid on an individual script basis
until PHP5.
Trev
Xenon_54
19-Dec-2004 10:27
The session support does not use the IP address for validation. It is
based on cookies and URL rewriting.
The reason you lose your session when closing your browser and
reconnecting to your ISP (so you are changing your IP), is that sessions
are only valides for the visit on your web site, not more.
Changing your IP address will not affect your session except if you
close your browser.
Michael Wells
22-Nov-2004 09:04
If you are trying to share sessions across a cluster of servers, and
don't want to use NFS, or a relatively heavy and slow RDBMS, there is an
excellent tool called ShareDance that can do it over a simple TCP
protocol. ShareDance comes complete with a PHP interface example and
works 'out of the box' for me.
http://sharedance.pureftpd.org/
For example, if you run script "SESS_TEST1.PHP" below, the local var
$animal will bleed its value of "I am an Elephant" into the session
variable $_SESSION['animal'], which should have a value of "I am a
Monkey". Beware!
<?php
// SESS_TEST1.PHP
session_start();
$_SESSION['animal'] = 'I am a Monkey';
$animal = 'I am an Elephant';
$value = 249;
echo "<script>window.location=\"sess_test2.php".
"?animal=$animal&value=$value\"</script>";
?>
<?php
// SESS_TEST2.PHP
session_start();
$animal = $_REQUEST['animal'];
$value = $_REQUEST['value'];
To avoid this, if you cannot ask your sysadmin to modify the php.ini
file, add this line to your .htaccess wherever you need it in your
application (usually on top of your app):
php_value session.auto_start 0
bcage at tecdigital dot net
23-Jun-2004 01:24
[Quote]
Someone posted a message here saying you should just all use the MM
shared memory management for sessions. I'd like to CAUTION EVERYONE
against using it!
Anyways, if you run a Unix machine that can map virtual memory to a
mount point (like tmpfs or shm or whatever it may be called), use this
instead. It's volatile like mm, but works. Only thing you don't get is
hidden session info so that other people don't know how to open it
easily - but it's better than trying to use mm and having the webserver
crash all the time!
[EndQuote]
rw,-s60000,,-b=4096,-f=512,-i=560,-c=3,-m=0,nosuid,nodev,nosymfollow
schulze at telstra dot com dot not dot this dot bit
06-Jun-2004 04:10
sessions not sticking and cookies not setting with IE? took me ages to
find the problem.
you need a 'compact privacy policy'! it's not hard once you know how!
Erich
Afternoon
04-May-2004 12:28
I found a good solution to create a persistent session by storing a
persistence flag, ironically, in the session itelf. I start the session
(which sends a Set-Cookie with no expiry time), read the flag and then,
if the user wants a persistent session, stop and restart the session
with the expiry time set using session_set_cookie_params, which then
sends a cookie with a good expiry time. This solution has been quickly
tested with all major browsers and seems to work.
$sHomeDirectory = 'http://my.server.com/one/of/my/projects'
which was used to make sure that all automatically generated links had
the right prefix (just like $cfg['PmaAbsoluteUri'] works in phpMyAdmin).
After introducing that variable, no link would pass the SID anymore,
causing every script to return to the login page. It took me hours (!!)
to recognize that this wasn't a bug in my code or some misconfiguration
in php.ini and then still some more time to find out what it was. The
above restriction had completely slipped from my mind (if it ever was
there...)
OK, it was my own mistake, of course, but it just shows you how easily
one can sabotage his own work for hours... Just don't do it ;)
tim at digicol dot de
04-Feb-2003 10:14
Be careful when using ini_set to change the session.gc_maxlifetime
value locally for your script:
You will trash other people's sessions when garbage collection takes
place (and they will trash yours) regardless of their (your) intended
session.gc_maxlifetime, because the session_name is not taken into
account during garbage collection.
session.cache_limiter = nocache
to:
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.
ricmarques at spamcop dot net
15-Oct-2000 05:16
Regarding session.cache_limiter :
For those of you who - like me - had trouble finding the meaning of the
possible values (nocache, public and private), here's the explaination
taken from the HTTP 1.1 Specification at
http://www.w3.org/Protocols/rfc2068/rfc2068
[snip]
public
Indicates that the response is cachable by any cache, even if it would
normally be non-cachable or cachable only within a non-shared cache.
(See also Authorization, section 14.8, for additional details.)
private
Indicates that all or part of the response message is intended for a
single user and MUST NOT be cached by a shared cache. This allows an
origin server to state that the specified parts of the response are
intended for only one user and are not a valid response for requests by
other users. A private (non-shared) cache may cache the response.
Note: This usage of the word private only controls where the response
may be cached, and cannot ensure the privacy of the message content.
no-cache
Indicates that all or part of the response message MUST NOT be cached
anywhere. This allows an origin server to prevent caching even by caches
that have been configured to return stale responses to client requests.
Note: Most HTTP/1.0 caches will not recognize or obey this directive."
shanemayer42 at yahoo dot com
19-Aug-2000 07:11
Session Garbage Collection Observation:
It appears that session file garbage collection occurs AFTER the current
session is loaded.
Show how to use and configure the PHP session management library
Use PHP session management to improve the client entry <form> in the winestore
case study
Provide a brief list of reasons for using, or avoiding, session management over the
Web
The focus of this chapter is on the session management provided by PHP. However, other
techniques to keep state are briefly discussed, including the use of cookies.
Most of this chapter is devoted to the second alternative, where the middle tier stores and
manages the application state using sessions. However, in this section we briefly discuss
solutions that store state in the client tier. One technique described in this section is the
use of cookies. While cookies can store state in the client tier, they are also used in
middle-tier session management, as described later in this chapter.
Data sent with the GET or POST methods can include the application state with each HTTP
request. An illustration of this approach can be seen in the previous and next browsing
features developed in Chapter 5. In this example, there are two pieces, or states, that need
to be considered when a page is browsed: the query parameters the user provided and
which page should be displayed.
The solution developed in Chapter 5 encodes the query and an offset as an embedded
link. An example URL that displays the fourth page of results may be as follows:
http://localhost/example.5-10.php?regionName=All&offset=40
This solution allows navigation through large search result sets. Similar solutions are
used in the URLs generated to jump between the results pages of web search engines
such as Google or Altavista. Cookies can be used for the same purpose.
Encoding the variables that hold state with each HTTP request increases the amount of
data that has to be transmitted over the Web, and when data is encoded using the GET
method, applications can generate long URLs. While HTTP doesn't restrict the length of
URLs, some older browsers and proxy servers do enforce limits.
When state variables are encoded as part of the URL, or even when they are included as
cookies, it is possible for the user to change the values that are sent with the request. For
example, a user can enter the following URL manually if she wants to see the records
starting from row #7 in the result set:
http://localhost/example.5-10.php?regionName=All&offset=7
Changing the offset in a results page is harmless, but changing the item price of a bottle
of wine is more serious. As discussed in Chapters 6 and 7, an application can't rely on
data that is sent from the browser.
Cookies
Cookies are often used to store application state in a web browser. As with data sent with
the GET or POST methods, cookies are sent with HTTP requests made by a browser. A
cookie is a named piece of information that is stored in a web browser. A browser can
create a cookie using JavaScript, but a cookie is usually sent from the web server to the
client in the Set-Cookie header field as part of an HTTP response. Consider an example
HTTP response:
HTTP/1.0 200
Content-Length: 1276
Content-Type: text/html
Date: Tue, 06 Nov 2001 04:12:49 GMT
Expires: Tue, 06 Nov 2001 04:12:59 GMT
Server: simwebs/3.1.6
Set-Cookie: animal=egg-laying-mammal
<html>...</html>
The web browser that receives this response remembers the cookie and includes it as the
header field Cookie in subsequent HTTP requests to the same web server. For example, if
a browser receives the response just shown, a subsequent request has the following
format:
There are several additional parameters used with the Set-Cookie header that define
when a cookie can be included in a request:
A cookie can have a date and time at which it expires. The browser includes the
cookie in requests up until that date and time. If no expiry date is given, the
cookie is remembered only while the browser is running. Cookies that are kept
only while the browser is running are known as session cookies.
A domain limits the sites to which a browser can send the cookie. If no domain is
set, the browser includes the cookie only in requests sent to the server that set the
cookie.
Browsers don't include the cookie in requests for resources that aren't in the
specified path. This is useful if only part of a web site requires that a cookie be
sent. For example, if the path is set to /admin, requests for resources in that path,
such as http://localhost/admin/home.php include the cookie, while requests
for resources in other paths, such as http://localhost/winestore/home.php,
do not.
A cookie can also be marked as secure, instructing the browser to send the
cookie only when using a secure connection through the Secure Sockets Layer
protocol. This prevents sensitive data stored in a cookie from being transmitted in
an insecure form. Encryption using the SSL software is discussed in Chapter 9.
Cookies can be included in an HTTP response using the header( ) function; however,
the developer needs to know how to encode the cookie name, value, and the other
parameters described earlier in the Set-Cookie header field. To simplify cookie creation,
PHP provides the setcookie( ) function that generates a correct header field.
When an HTTP request that contains cookies is processed, PHP makes the values of the
cookies available to the script in the global associative array $HTTP_COOKIE_VARS. If
register_globals is enabled, a variable with the name of the cookie is also initialized
by PHP; the register_globals feature in the php.ini file is discussed in Chapter 5.
Example 8-1 tests to see if the variable $count has been set from a cookie, and either sets
the value to 0 or increments $count accordingly. The script also creates a cookie named
start, with the value set to the current time, when the $count is set to 0. The cookie
start is set only at the beginning of this stateful interaction.
<?php
} else {
$count++;
}
?>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head><title>Cookies</title></head>
<body>
<p>This page comes with cookies: Enjoy!
<br>count = <?=$count ?>.
<br>start = <?=$start ?>.
<p>This session has lasted
<?php
$duration = time( ) - $start;
echo "$duration";
?>
seconds.
</body>
</html>
The setcookie( ) function is called with six arguments, although only the first--the
name--is required:
The two calls to setcookie( ) in Example 8-1 add the Set-Cookie header field to the
HTTP response. The first encodes the start cookie with the value of the current time as
an integer returned from the time( ) function. The second encodes the count cookie
with the value of the variable $count. Both cookies are set with the expiry date of the
current time plus 600 seconds; that is, 10 minutes. With the path parameter set to /, the
browser includes the cookies with all requests to the site. By passing an empty string for
the domain, the browser includes the cookies only with requests to the domain of the
machine serving this page. The final parameter 0 allows the browser to transmit the
cookies over both secure and insecure connections.
Cookies can be used for simple applications that don't require complex data to be kept
between requests. However, there is a limit on the number and size of cookies that can be
set: a browser can keep only the last 20 cookies sent from a particular domain, and the
values that a cookie can hold are limited to 4 KB in size. Also, there are arguments about
both the privacy and the security of applications that use cookies, and users often disable
cookie support in their browsers. We discuss some of the security issues of cookies in
Chapter 9.
Owing to the fact that HTTP is stateless that is, any data you have stored is forgotten
about when the page has been sent to the client and the connection is closed it took a
little work to find a solution to the problem. Eventually, Netscape put a solution into their
browser known as "cookies" tiny bits of information that a web site could store on the
client's machine that were sent back to the web site each time a new page was requested.
Each cookie could only be read by the web site that had written it, meaning that it was a
secure way to store information across pages.
Cookies earned a bad name at first because they allowed people to track how often a
visitor came to their site, what they did on the site, and such, and many people believed
that cookies signalled the end of privacy on the web. Urban myths popped up in many
places saying that cookies can read any information from your hard drive, and people
were encouraged to disable cookies across the board. The reality is, of course, that
cookies are relatively harmless, and are now commonly accepted.
Sessions grew up from cookies as a way of storing data on the server side, because the
inherent problem of storing anything sensitive on clients' machines is that they are able to
tamper with it if they wish. In order to set up a unique identifier on the client, sessions
still use a small cookie this cookie simply holds a value that uniquely identifies the
client to the server, and corresponds to a data file on the server.
[edit]
Chapter contents
9.1. Cookies vs sessions
o 9.1.1. Cookies
o 9.1.2. Sessions
9.1.3. Choosing the appropriate option
9.2. Using cookies
9.3. Using sessions
o 9.3.1. Starting a session
o 9.3.2. Adding session data
o 9.3.3. Reading session data
o 9.3.4. Deleting session data
o 9.3.5. Ending a session
o 9.3.6. Checking whether a session variable is set
o 9.3.7. Files vs databases for sessions
9.4. Storing complex data types in sessions
Next: Cookies vs sessions
Both cookies and sessions are available to you as a PHP developer, and both accomplish
much the same task of storing data across pages on your site. However, there are
differences between the two that will make each favourable in their own circumstance.
Cookies can be set to a long lifespan, which means that data stored in a cookie can be
stored for months if not years. Cookies, having their data stored on the client, work
smoothly when you have a cluster of web servers, whereas sessions are stored on the
server, meaning if one of your web servers handles the first request, the other web servers
in your cluster will not have the stored information.
Sessions are stored on the server, which means clients do not have access to the
information you store about them this is particularly important if you store shopping
baskets or other information you do not want your visitors to be able to edit by hand by
hacking their cookies. Session data, being stored on your server, does not need to be
transmitted with each page; clients just need to send an ID and the data is loaded from the
local file. Finally, sessions can be any size you want because they are held on your server,
whereas many web browsers have a limit on how big cookies can be to stop rogue web
sites chewing up gigabytes of disk space with meaningless cookie information.
So, as you can see, each have their own advantages, but at the end of the day it usually
comes down to one choice: do you want your data to work when you visitor comes back
the next day? If so, then your only choice is cookies if you have any particularly
sensitive information, your best bet is to store it in a database, then use the cookie to store
an ID number to reference the data. If you do not need semi-permanent data, then
sessions are generally preferred, as they are a little easier to use, do not require their data
to be sent in entirety with each page, and are also cleaned up as soon as your visitor
closes their web browser.