PHP: Session handling functions - Manual
PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previoussesam_settransactionsession_cache_expirenext
Last updated: Wed, 24 Jul 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Czech | Dutch | Finnish | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

XCII. Session handling functions

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.

If you are familiar with the session management of PHPLIB, you will notice that some concepts are similar to PHP's session support.

A visitor accessing your web site is assigned an 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.

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.

The track_vars and register_globals configuration settings influence how the session variables get stored and restored.

ע: As of PHP 4.0.3, track_vars is always turned on.

ע: 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.

If track_vars is enabled and register_globals is disabled, only members of the global associative array $HTTP_SESSION_VARS can be registered as session variables. The restored session variables will only be available in the array $HTTP_SESSION_VARS.

���� 1. Registering a variable with track_vars enabled

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

Use of $_SESSION (or $HTTP_SESSION_VARS with PHP 4.0.6 or less) is recommended for security and code readablity. With $_SESSION or $HTTP_SESSION_VARS, there is no need to use session_register()/session_unregister()/session_is_registered() functions. Users can access session variable like a normal variable.

���� 2. Registering a variable with $_SESSION.

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

���� 3. Unregistering a variable with $_SESSION.

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

If register_globals is enabled, then all global variables can be registered as session variables and the session variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users must register variables with session_register() function while $HTTP_SESSION_VARS/$_SESSION does not need to use session_register().

ע��

If you are using $HTTP_SESSION_VARS/$_SESSION and disable register_globals, do not use session_register(), session_is_registered() and session_unregister().

If you enable register_globals, session_unregister() should be used since session variables are registered as global variables when session data is deserialized. Disabling register_globals is recommended for both security and performance reason.

���� 4. Registering a variable with register_globals enabled

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

If both track_vars and register_globals are enabled, then the globals variables and the $HTTP_SESSION_VARS/$_SESSION entries will reference the same value for already registered variables.

If user use session_register() to register session variable, $HTTP_SESSION_VARS/$_SESSION will not have these variable in array until it is loaded from session storage. (i.e. until next request)

There are two methods to propagate a session id:

  • Cookies

  • URL parameter

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

PHP is capable of doing this transparently when compiled with --enable-trans-sid. If you enable this option, relative URIs will be changed to contain the session id automatically. 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 arg_separator.output php.ini directive allows to customize the argument seperator.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

���� 5. Counting the number of hits of a single user

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

Hello visitor, you have seen this page <?php echo $count; ?> times.<p>;

<?php
# the <?php echo SID?> (<?=SID?> can be used if short tag is enabled) 
# is necessary to preserve the session id
# in the case that the user has disabled cookies
?>

To continue, <A HREF="nextpage.php?<?php echo 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 session.save_path's path depth is more than 2, garbage collection will not be performed.

    ����

    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.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Defaults to 0 (disabled, for backward compatibility). Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0.

  • 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 (none/nocache/private/private_no_expire/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 transparent 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 transparent 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_cache_expire -- Return current cache expire
session_cache_limiter -- Get and/or set the current cache limiter
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 if a 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_readonly -- Begin session - reinitializes freezed variables, but no writeback on request end
session_register --  Register one or more 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 variable from the current session
session_unset --  Free all session variables
session_write_close -- Write session data and end session
User Contributed Notes
Session handling functions
add a note about notes

18-Feb-2000 11:40

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


30-Jun-2000 03:29

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

2) If you want a session handler for mysql: 


08-Aug-2000 10:09

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


13-Aug-2000 01:27

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

That means before the session_start()!


20-Aug-2000 01:11

Session Garbage Collection Observation:

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

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


30-Aug-2000 04:25

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

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

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

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

[email protected]:

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

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

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

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

<PRE>

if (getenv(HTTP_X_FORWARDED_FOR)){ 

$ip=getenv(HTTP_X_FORWARDED_FOR); 

} 

else { 

$ip=getenv(REMOTE_ADDR); 

} 

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

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

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


15-Oct-2000 11:16

Regarding session.cache_limiter :

For those of you who - like me - had trouble finding the meaning of the
possible values (nocache, public and private), here's the explaination
taken from the HTTP 1.1 Specification at



"14.9.1 What is Cachable

[snip]

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

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

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

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

  Note: Most HTTP/1.0 caches will not recognize or obey this
directive."


11-Dec-2000 12:32

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

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

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


15-Dec-2000 10:58

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

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


16-Dec-2000 01:41

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

  

This uses the ADODB database wrapper library.


28-Dec-2000 02:49

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

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

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


13-Mar-2001 04:15

How to fallback from COOKIE session to URL:

According to zend.com

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

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

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


03-May-2001 04:03

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

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


10-May-2001 10:14

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

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


03-Jun-2001 06:53

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

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

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


19-Jul-2001 04:59

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

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


21-Jul-2001 04:25

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

<?php

$SID = "";				// declare global

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

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

?>


31-Jul-2001 11:12

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


03-Oct-2001 01:23

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



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



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

foreach($expected_vars as $key)

    if($HTTP_GET_VARS[$key])

      $$key=$HTTP_GET_VARS[$key];

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



Michael


03-Nov-2001 06:40

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


17-Jan-2002 04:30

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

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

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

Hope it helps! :)


11-Feb-2002 08:47

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


19-Feb-2002 01:18

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

<?php 

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

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

?>

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

Comments? Send a mail!

Tim

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

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

Arjan.



variables_order  string

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


08-Mar-2002 06:48

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

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

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


20-Mar-2002 02:24

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

extremly simplified:

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

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

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

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


20-Mar-2002 03:10

Carefull when you are working in PHP with WML. The arg separator used to
put de PHPSESSID variable in URL is '&' by default, and this cause a
Compile Error in browsers:

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

instead of this:

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

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

to change the arg separator, it worked in PHP 4.1.2

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

* In most case the WAP GateWay accepts cookies an the auto-transpass-SID
is not necessary, it�s hard to find problems with this.


16-Apr-2002 06:19

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

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

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

replace PHPSESSID with your php session name (session_name)

rene_AT_cola.cc
26-Apr-2002 06:10

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


05-May-2002 09:21

Here is the output of 2 hours of stress.

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

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

Regards,
OS

Joerg Aldinger
10-May-2002 10:26

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

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


12-May-2002 04:58

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

twocandles3000@hotmail
14-May-2002 05:34

Storing class instances in session.

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

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

Following this steps, the session is started at every page and myclass is
always available, avoiding to write the session_start() function at every
page.

php 4.2.0 and 4.2.1, Apache 1.3 and W2K Pro.

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

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


25-May-2002 08:01

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

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

Gregory


26-May-2002 06:50

REGARDING:

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

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

This is a crock of shit.

So its a security risk to leak the SID?

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

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

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

Sincerely,
Mr. My Site Got Hacked.

READ THIS:


The HTTP_REFERER problem

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

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



My first version of the script looked like this:

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

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

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

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


31-May-2002 01:32

somebody might need this (like me)

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

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


10-Jun-2002 05:48

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


12-Jun-2002 02:31

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


20-Jun-2002 06:15

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

add a note about notes
previoussesam_settransactionsession_cache_expirenext
Last updated: Wed, 24 Jul 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Mon Jul 29 00:09:02 2002 CEST