略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: session_id

2024-11-14

session_id

(PHP 4, PHP 5, PHP 7, PHP 8)

session_id获取/设置当前会话 ID

说明

session_id(string $id = ?): string

session_id() 可以用来获取/设置 当前会话 ID。

为了能够将会话 ID 很方便的附加到 URL 之后, 你可以使用常量 SID 获取以字符串格式表达的会话名称和 ID。 请参考 会话处理

参数

id

如果指定了 id 参数的值, 则使用指定值作为会话 ID。 必须在调用 session_start() 函数之前调用 session_id() 函数。 不同的会话管理器对于会话 ID 中可以使用的字符有不同的限制。 例如文件会话管理器仅允许会话 ID 中使用以下字符:a-z A-Z 0-9 , (逗号)和 - (减号)

注意: 如果使用 cookie 方式传送会话 ID,并且指定了 id 参数, 在调用 session_start() 之后都会向客户端发送新的 cookie, 无论当前的会话 ID 和新指定的会话 ID 是否相同。

返回值

session_id() 返回当前会话ID。 如果当前没有会话,则返回空字符串("")。

参见

add a noteadd a note

User Contributed Notes 22 notes

up
30
Riikka K
7 years ago
It may be good to note that PHP does not allow arbitrary session ids. The session id validation in PHP source is defined in ext/session/session.c in the function php_session_valid_key:

https://github.com/php/php-src/blob/master/ext/session/session.c

To put it short, a valid session id may consists of digits, letters A to Z (both upper and lower case), comma and dash. Described as a character class, it would be [-,a-zA-Z0-9]. A valid session id may have the length between 1 and 128 characters. To validate session ids, the easiest way to do it use a function like:

<?php

function session_valid_id($session_id)
{
    return
preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}

?>

session_id() itself will happily accept invalid session ids, but if you try to start a session using an invalid id, you will get the following error:

Warning: session_start(): The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'
up
-7
ab at ixo point ca
11 years ago
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.
up
-7
gmillikan at t1shopper dot com
7 years ago
session_id() URL-decodes the session value.   For example let's say we use setcookie() to push a cookie down to a web browser.  When the browser makes the next page request the browser sends the cookie back up to us with headers like this:  Cookie: PHPSESSID=enGHumY%2C-2De-F-TDzNHVmE%2ChY5;

If we use session_id() to read the cookie it will output a value of this: enGHumY,-2De-F-TDzNHVmE,hY5

The two values don't match!  Use either setrawcookie() or URL encode if you wish to match the original value.
up
-8
ohcc at 163 dot com
5 years ago
When session.use_strict_mode is set to 1 or true, you cannot use session_id($sid) to set the session id for the current session.
<?php
    ini_set
('session.use_strict_mode', 1);
   
$sid = md5('wuxiancheng.cn');
   
session_id($sid);
   
session_start();
   
var_dump(session_id() === $sid);// always false
?>
up
-6
dmeweb at dibsplace dot com
11 years ago
If you look at the notes on cookies (set_cookie I think), you will see that you can not read a cookie on the page that it is set.  That is because the cookies are sent with the page request which comes, of course, before your PHP is run.  You have to wait until the next page request from the same source to read the cookie.
up
-4
Igor Oliveira Ferreira
6 years ago
This can looks obvious, but as me, you can spend some hours to make a simple session work between different browsers and devices. These are the basics for me, but you can build upon.

<?php
if($_GET){
   
//defining the session_id() before session_start() is the secret
   
session_id($_GET['session_id']);
   
session_start();
    echo
"Data: " . $_SESSION['theVar'];
   
//use your data before below commands
   
session_destroy();
   
session_commit();
}else{
   
//common session statement goes here
   
session_start();
   
$session_id=session_id();
   
$_SESSION['theVar'] = "theData";
    echo
"your.php?session_id=" . $session_id;
}
?>
up
-4
Shiji Jiang
7 years ago
IMPORTANT NOTE:
If you assign a specific session ID to a user in your applet, then do not run the following code either while logout,
session_regenerate_id(TRUE);
USE:
session_regenerate_id();   instead.
OTHERWISE, setting the session id will no longer works for that user.
up
-8
jpjounier at hotmail dot com
16 years ago
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
}
?>
up
-9
Anonymous
15 years ago
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.
up
-7
karlhaines at comcast dot net
18 years ago
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!
up
-14
cbarnes at bfinity dot net
17 years ago
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();
}
?>
up
-9
simon at quo dot com dot au
16 years ago
Length of PHPSESSID appears to be 32 characters by default.
up
-16
Dario Gomes
11 years ago
Gosh, took a LOOONG time to figure this one out! If you have suhosin built into your PHP and can't get sessions to work after changing the session id through session_id(), try turning off suhosin's session encryption option in php.ini with:

suhosin.session.encrypt=Off
up
-10
hela69
4 years ago
The call session_id(null) and session_id() provides not the same result. It is imperative to pass no parameters to get correct results.
up
-10
Anonymous
15 years ago
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
up
-15
Colin
15 years ago
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.
up
-13
Drugelis, Lietuva
11 years ago
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.
up
-18
Axel
14 years ago
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
up
-19
Francois
11 years ago
In php version 5.3.2 in my case each time a new session-id was generated after session_start() but all was working before correctly in previous versions. So I lost data from my current session (wrong session-id). There was always a $_POST or $_GET or $_COOKIE available with the session-name and session-id, so session_start() was taken this automatically. Now I have to execute session_id(..old id ..) before session_start() and a session is started for the same id.
up
-17
Andi, info at pragmaMx dot org
19 years ago
you can also add the iframe tag:
ini_set("url_rewriter.tags", "a=href,area=href,frame=src,iframe=src,input=src,form=fakeentry");
up
-29
infinito84 at gmail dot com
8 years ago
Get a shared session.

Sometimes is good can interchange messages and vars between one session and another, but PHP dont support this. I create this script that allows with session_id() change from current session to shared session (this is, info with scope to all sessions) for read and write info and back in to user session. The code:

<?php
    ini_set
('display_errors',1);
   
error_reporting(E_ALL);
   
    function
get_global($key){
       
//Get current session
       
if(session_status()!=PHP_SESSION_ACTIVE)session_start();
       
$current_id=session_id();
       
session_write_close();
       
//Set a global session with session_id=1
       
session_id(1);
       
session_start();
       
//Get superglobal value
       
$value=null;
        if(isset(
$_SESSION[$key]))$value=$_SESSION[$key];
       
session_write_close();
       
//Set the before session
       
session_id($current_id);
       
session_start();
        return
$value;
    }
   
    function
set_global($key,$value){
       
//Get current session
       
if(session_status()!=PHP_SESSION_ACTIVE)session_start();
       
$current_id=session_id();
       
session_write_close();
       
//Set a global session with session_id=1
       
session_id(1);
       
session_start();
       
//Set superglobal value
       
$_SESSION[$key]=$value;
       
session_write_close();
       
//Set the before session
       
session_id($current_id);
       
session_start();
    }
   
//Example
    //Begin my session normally
   
session_start();
    if(empty(
$_SESSION['count'])){
       
$_SESSION['count']=0;
       
$_SESSION['color']="rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";
    }
   
$_SESSION['count']++;
   
$id=session_id();
   
//Get the superglobal
   
$test=get_global("test");
   
//Set the superglobal test with empty array if this dont set
   
if($test==null)$test=array();
   
//Get the superglobal
   
$test=get_global("test");
   
//Set values for each reload page and save the session_id that create it
   
$test[]="<span style='color:".$_SESSION['color']."'>Value: ".rand(0,100)." SessionID: $id</span><br>";
   
//Save the superglobal
   
set_global("test",$test);
   
//Show the superglobal
   
foreach($test as $t){
        echo
$t;
    }
    echo
"<b>Reloads = ".$_SESSION['count'].", <span style='color:".$_SESSION['color']."'>This my color</span></b>";
   
    exit;
?>
up
-60
jeff_zamrzla
17 years ago
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;
}
?>

官方地址:https://www.php.net/manual/en/function.session-id.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3