PHP Doku:: Liefert und/oder setzt die aktuelle Session-ID - function.session-id.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSession-ErweiterungenSessionbehandlungSession-Funktionensession_id

Ein Service von Reinhard Neidl - Webprogrammierung.

Session-Funktionen

<<session_get_cookie_params

session_is_registered>>

session_id

(PHP 4, PHP 5)

session_idLiefert und/oder setzt die aktuelle Session-ID

Beschreibung

string session_id ([ string $id ] )

session_id() wird verwendet, um die Session-ID der aktuellen Session zu erhalten oder zu setzen.

Die Konstante SID kann auch dazu verwendet werden, den aktuellen Namen und die Session-ID als Zeichenkette passend zum Anhängen an URLs zu erhalten. Siehe auch Session Funktionen.

Parameter-Liste

id

Wenn id angegeben wird, wird die die aktuelle Session-ID ersetzt. session_id() muss zu diesem Zweck vor session_start() aufgerufen werden. In Abhängigkeit von der Session-Prozedur sind in der Session-ID nicht alle Zeichen erlaubt. Zum Beispiel erlaubt die dateibasierte Session-Prozedur nur Zeichen im Bereich a-z A-Z 0-9 , (Komma) und - (Minus)!

Hinweis: Falls Session-Cookies verwendet werden und für session_id() eine id angegeben wird, wird ungeachtet dessen, ob die aktuelle Session-ID mit der neuen identisch ist, bei jedem Aufruf von session_start() ein neues Cookie gesendet.

Rückgabewerte

session_id() gibt die Session-ID der aktuellen Session zurück oder die leere Zeichenkette (""), falls es keine aktuelle Session gibt (es existiert keine aktuelle Session-ID).

Changelog

Version Beschreibung
5.0.0 Die Zeichen , (Komma) und - (Minus) sind in der dateibasierten Session-Prozedur zulässig.

Siehe auch


17 BenutzerBeiträge:
- Beiträge aktualisieren...
ab at ixo point ca
7.01.2011 20:17
I was perplexed by inconsistent results with the session ID depending on whether I retrieve it using SID, COOKIE, or session_id().  I have found that session_id() is the most reliable method, whereas SID and COOKIE["PHPSESSIONID"] are sometimes undefined.

I used this simple script to quickly test the problem on my servers:

<?php
$a
= session_id();
if(empty(
$a)) session_start();
echo
"SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>

Regardless of browser I see the COOKIE undefined on the first load and the other two defined, then SID is empty on subsequent reloads and COOKIE is defined, but session_id() is always defined.

If I insert the session_regenerate_id() method that jeff_zamrzla gives below the refresh the page, I get a new session_id() but the COOKIE value is initially the prior session_id() until I hit refresh a second time.  So again, session_id() proves to be the most reliable method.

It's probably not a bug since I found the behaviour to be consistent in PHP versions 5.2.14, 5.3.3 and 5.3.4, but I can't figure what I'm missing and hopefully this will help others who run into this.
Drugelis, Lietuva
11.09.2010 16:46
I had a lot of trouble with session_regenerate_id() as it did not regenerate... Session_id() stayed the same no matter what (unless closing the window). I wanted to have different sid and empty vars for each session/page meeting a condition for security reasons.  Finally, this worked:

<?php
$a
= session_id();
if (
$a == '') session_start();
if ( ...
add check if you want to regenerate and destroy vars on some condition only [recommended :)]...  )
 {
session_unset(); //destroys variables
  
session_destroy() //destroys session;
 
}

$a = session_id();
if (
$a == '') session_start();
if (!isset(
$_SESSION['safety']))
{
   
session_regenerate_id(true);
   
$_SESSION['safety'] = true;
}
$_SESSION['sessionid'] = session_id();
?>

Now you get different sid and session variables empty for each session_start if condition is met (i.e. user hits refresh on user/password form, which I needed badly :). Hope this helps someone out there.
Env: localhost
Note: condition is mandatory, otherwise it destroys on each load.
strick
30.09.2008 21:01
I was having trouble with the whole session staying intact when opening a new window with window.open().

I tried just about everything and nothing work.  So I did a simple test case and found the corlput.

<?php

$mytimeout
= 720 * 60; // minutes * 60
session_set_cookie_params($mytimeout);

$sessdir = "my\path\to\sessions";
ini_set('session.save_path', $sessdir);

session_cache_expire($mytimeout / 60);
set('session.gc_maxlifetime', $mytimeout);

?>

You have to repeat this same bit of coding inside of your popup.php, duh!!
Axel
13.05.2008 10:44
The documentation for session_id is incomplete when it says:
"For example, the file session handler only allows characters in the range a-z, A-Z and 0-9!".

It is untrue when changing the default for the session.hash_bits_per_character as Colin said. session_id may therefore contain "-" and ",".

http://fr.php.net/manual/en/session.configuration.php
dnaicker at gmail dot com
22.10.2007 22:33
I was using session_id but i needed to send more than one variable across to another php page. I was trying to create a link to an xml file and i needed to send the name of the file to another php document to open the file using DOM or SimpleXML.

I sent the variable across in the hyperlink and gathered the variable using the $_POST['$VarName'] command.

This is the code i used:
Page1:

echo"\t\t<td><a href=\"showArticle.php?file=".$title."\" name=\"$title\">View Article</a></td>\n";

Page2:
$file = $_GET["file"];
Nicu
7.07.2007 0:22
Saving sessions to file and generating the ID's with Sha1 and 6 bit/character on Windows machines gives a higher chance of session collision (the filesystem is not case sensitive)

25.03.2007 21:06
Regarding Colin's comment, note that setting hash_bits_per_character to 5 results in characters ranging from 0-9 and a-v. Most attackers would be wise enough to realize what was going on when they saw a letter in g-v.  The probability of not seeing a letter in g-v is somewhere around 2^-32.
Colin
8.03.2007 19:46
The higher you set session.hash_bits_per_character the shorter your session_id will become by using more bits per character. The possible values are 4, 5, or 6.

When using sha-1 for hashing (by setting ini_set('session.hash_function', 1) the following session string lengths are produced by the three session.hash_bits_per_character settings:

4 - 40 character string
5 - 32 character string
6 - 27 character string

It would seem desirable to use sha-l with 5 bits_per_character because this will emulate a standard 32 character md5 string and make a would-be attacker think that is what you're hashing with.
masternico at yahoo dot fr
14.01.2007 16:03
in addition to what said "jpjounier at hotmail dot com" it's EXTREMELY important to test if "session_id()" gives a result or not.

If you do not, you take the risk to have a new session starting over with the loss of your session variables.

php.ini can be different on each webserver you'll host your script on.

If you only rely on the behavior of your script on one server, you might have trouble on others.

One VERY important session's option of php.ini is 'session.auto_start' . If setted at 'true', session will then start automaticaly for each page that user will open without the need of using session_start().

The point is that if you have a script like this one:
/*****************
verif_logging.php:
*****************/
<?php
   
include('includes/class_user');   
   
$login = $_POST['login'];
   
$pass = $_POST['pass'];
    if(
$user->connection($login,$pass){ // user logging validation
       
session_start();     //start the session
       
$_SESSION['user_logged'] = true// user logged in
       
header('location : control_panel.php');  // go to control panel
   
}
    else { 
// go back to logging page
       
header('location : logging.php?' . $user->error_string);
    }
?>

/****************
control_panel.php:
****************/
<?php
    session_start
();
    echo
$_SESSION['user_logged'];
?>

All will be ok as long as 'session.auto_start ' is at 'false'. Otherwise, you'll have a brand new session created with empty $_SESSION and new SID.

This has been brain breaker for me until I realise that my webserver has 'session.auto_start' at 'true' and that I couldn't change it (some webhost doesn't let user change php.ini options).

So I changed the code this way:
/***************
control_panel.php:
***************/
<?php
   
if (session_id() == "") session_start(); // if no active session we start a new one
   
echo $_SESSION['user_logged'];
?>

And then everything is ok regardless if 'session.auto_start' is set to 'false' or 'true'.

Furthermore, as said 'risaac at deadletter dot com' (04-Apr-2006 08:46) in a comment on 'session_write_close()', it might be a clever thing to check if the newly activated session has $_SESSION empty or setted with the value you passed by as expected. If empty, then you might have launched a brand new session and surely lost every fromer data unless you know what was the SID (passed by $_GET for example, not recommended but possible).

22.08.2006 10:15
In response to simon at quo dot com dot au:

The PHPSESSID is produced using an hash function. By default, it uses MD5 which produces 128 bits long (i.e: 16 bytes long) hashes.
But, since some bytes' values may not be used in the HTTP header, PHP outputs the hash in its hexadecimal representation, thus resulting in a 32 bytes long text.

Starting with  PHP 5.0, you can change the hash function used (by setting "session.hash_function" to whatever function you want to use in php.ini).
You may for example set it to 1 to switch to SHA-1 which produces 160 bits (20 bytes) long hashes.

Please also note that another setting was introduced in PHP 5 (session.hash_bits_per_character) which sort of "compresses" the hash. Thus, resulting in what seems to be a shorter hash.
This feature helps you improve your application's security by producing IDs that are harder to prodict for a malicious attacker.

More information on those settings is provided on:
http://www.php.net/manual/en/ref.session.php
simon at quo dot com dot au
6.03.2006 19:15
Length of PHPSESSID appears to be 32 characters by default.
jwhatcher at hotmail dot com
7.07.2005 21:21
Killing the session_id when using cookies to store the session_id. Useful when needing to recreate a user with different session information during an open session.

    unset($_COOKIE[session_name()]);
    session_start();
jpjounier at hotmail dot com
23.06.2005 13:28
About the note from Cybertinus :

The following test doesn't work, the code following is always executed :

<?php
if(!session_id())
{
// Always executed even if there's already an opened session
}

session_id() returns an empty string if there is no current session, so to test if a session already exists, it's better to write this :
if(session_id() == "")
{
session_start();
}
else
{
// Anything you want
}
?>
cbarnes at bfinity dot net
10.05.2005 3:44
Note that Firefox and Mozilla use the same process for launching new windows or tabs, they will pick up the same session id as the previous windows until the parent process dies or is closed. This may cause undesired results if the session id is stored in a db and checked, a solution is to check at the new entry point (new tab or window if the user went back to the index page) for an existing session. If a session id exists and a new one is required use something like:

<?php
$ses_id
= session_id();
$bsid_exists = false;
$bsid_exists = check_session_id_from_db($ses_id);
 if (
$bsid_exists){
 
//This is a reentry and the session already exists
 // create a new session ID and start a new
session_regenerate_id();        
$ses_id = session_id();
 }
?>
jeff_zamrzla
11.02.2005 0:03
Try this code snippet, from a book by a security expert who says this is more secure to place on every page:

<?php
session_start
();
$_SESSION['name'] = "YourSession";

if (!isset(
$_SESSION['initiated']))
{
   
session_regenerate_id();
   
$_SESSION['initiated'] = true;
}
?>
karlhaines at comcast dot net
31.10.2003 2:05
Rewriting URL's is not suggested for obvious security issues. Please be careful with register_globals when using sessions! Check that all information you recieve from a user is valid before accepting it!
Andi, info at pragmaMx dot org
16.01.2003 22:13
you can also add the iframe tag:
ini_set("url_rewriter.tags", "a=href,area=href,frame=src,iframe=src,input=src,form=fakeentry");



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)