百科狗-知识改变命运!
--

session_start() - php 会话函数session

乐乐1年前 (2023-11-21)阅读数 15#技术干货
文章标签函数

session_start()

(PHP 4, PHP 5, PHP 7)

启动新会话或者重用现有会话

说明

session_start([array $options= array()]): bool

session_start()会创建新会话或者重用现有会话。如果通过 GET 或者 POST 方式,或者使用 cookie 提交了会话 ID,则会重用现有会话。

当会话自动开始或者通过session_start()手动开始的时候, PHP 内部会调用会话管理器的 open 和 read 回调函数。会话管理器可能是 PHP 默认的,也可能是扩展提供的(SQLite 或者 Memcached 扩展),也可能是通过session_set_save_handler()设定的用户自定义会话管理器。通过 read 回调函数返回的现有会话数据(使用特殊的序列化格式存储), PHP 会自动反序列化数据并且填充$_SESSION 超级全局变量。

session_start() - php 会话函数session

要想使用命名会话,请在调用session_start()函数之前调用session_name()函数。

如果启用了session.use_trans_sid选项,session_start()函数会注册一个内部输出管理器,该输出管理器完成 URL 重写的工作。

如果用户联合使用ob_start()和ob_gzhandler函数,那么函数的调用顺序会影响输出结果。例如,必须在开始会话之前调用ob_gzhandler函数完成注册。

参数

$options

此参数是一个关联数组,如果提供,那么会用其中的项目覆盖会话配置指示中的配置项。此数组中的键无需包含session.前缀。

除了常规的会话配置指示项,还可以在此数组中包含read_and_close选项。如果将此选项的值设置为TRUE,那么会话文件会在读取完毕之后马上关闭,因此,可以在会话数据没有变动的时候,避免不必要的文件锁。

返回值

成功开始会话返回TRUE,反之返回FALSE

更新日志

版本说明
7.1.0session_start()执行失败,无法开始一个会话的时候,会返回FALSE,并且不会初始化超级变量$_SESSION。
7.0.0新加$options参数。
5.3.0如果函数调用失败返回FALSE,之前版本返回了TRUE

范例

基本的会话示例

Example #1page1.php

The constant SID would always be '' (an empty string) if directive session.use_trans_sid in php ini file is set to 0. 
So remember to set session.use_trans_sid to 1 and restart your server before you use SID in your php script.
If you open a popup window (please no commercial ones!) with javascript window.open it might happen IE blocks the session cookie.
A simple fix for that is opening the new window with the session ID in a GET value. Note I don't use SID for this, because it will not allways be available.
----page.php----
//you must have a session active here
window.open('popup.php?sid=', '700x500', 'toolbar=no, status=no, scrollbars=yes, location=no, menubar=no, directories=no, width=700, height=500');
----popup.php---- 
Unfortunately, after pulling my hair out trying to figure out why my application was working fine in every browser other than IE ( Internet Explorer) (Opera, Chrome, Firefox, Safari are what I've tested this in) - when using a DNS CNAME record (like a vanity name that is different from the DNS A record, which is the hostname of the server) sessions do not work correctly.
If you store a session var while on the CNAME:
vanity.example.com and the hostname of the server is hosname.example.com
Then try to call the variable from a different page, it will not find it because of the CNAME (I guess it store the variable under the hostname, then when trying to read it it's still looking under the CNAME) the same application works fine when accessing it under the hostname directly. Keep in mind that I was testing this on an internal network.
I recently made an interesting observation:
It seems that `session_start()` can return `true` even if the session was not properly created. In my case, the disk storage was full and so the session data could not be written to disk. I had some logic that resulted in an infinite loop when the session was not written to disk.
To check if the session really was saved to disk I used:
```

```
Took me quite a while to figure this out. 
Maybe it helps someone!
PHP locks the session file until it is closed. If you have 2 scripts using the same session (i.e. from the same user) then the 2nd script will not finish its call to session_start() until the first script finishes execution.
If you have scripts that run for more than a second and users may be making more than 1 request at a time then it is worth calling session_write_close() as soon as you've finished writing session data.

Found this out from http://konrness.com/php5/how-to-prevent-blocking-php-requests/
A session created with session_start will only be available to pages within the directory tree of the page that first created it.
i.e. If the page that first creates the session is /dir1/dir2/index.php and the user then goes to any page above dir2 (e.g. /dir1/index.php), session_start will create a new session rather than use the existing one.
X Maintainers ... Sorry to be such pain the ass, please delete this duplicate, because submitted in a crazy 'session' where i've mess things between browser tabs ... sorry again, alessio
http://php.net/manual/en/function.session-start.php#121310
If you are using a custom session handler via session_set_save_handler() then calling session_start() in PHP 7.1 you might see an error like this:
session_start(): Failed to read session data: user (path: /var/lib/php/session) in ...
As of this writing, it seems to be happening in PHP 7.1, and things look OK in PHP7.0. 
It is also hard to track down because if a session already exists for this id (maybe created by an earlier version of PHP), it will not trigger this issue because the $session_data will not be null.
The fix is simple... you just need to check for 'null' during your read function: 
PHP Manual specifically denotes this common mistake:
Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!
See session_id() manual page for more details.
3 easy but vital things about Sessions in AJAX Apps.

Hope this helps someone with their sessions...
Thanks.
When you have an import script that takes long to execute, the browser seem to lock up and you cannot access the website anymore. this is because a request is reading and locking the session file to prevent corruption.
you can either 
- use a different session handler with session_set_save_handler()
- use session_write_close() in the import script as soon you don't need session anymore (best moment is just before the long during part takes place), you can session_start when ever you want and as many times you like if your import script requires session variables changed. 
example 
If you ever need to open multiple distinct sessions in the same script and still let PHP generate session ids for you, here is a simple function I came up with (PHP default session handler is assumed):

When using this function, session_start() should not be called on its own anymore (can be replaced with a call to session_switch() without argument).
Also remember that session_start() sets a Set-Cookie HTTP header on each call, so if you echo in-between sessions, wrap with ouput buffering.
Note: it's probably rarely a good idea to handle multiple sessions so think again if you think you have a good use for it.
Personally it played its role for some quick patching of legacy code I had to maintain.
I just need with easy, count how many times the page reload over the site, may to add a warning popup, while the counter is 0:
session_start();
if(isset($_SESSION['count'])){
$count = $_SESSION['count'];
$count++; 
$count = $_SESSION['count'] = $count;
} else {
  $count = $_SESSION['count'] = 0;
}
echo $count;
//session_destroy();
Be warned that depending on end of script to close the session will effectively serialize concurrent session requests.  Concurrent background "data retrieval" (e.g. applications such as AJAX or amfphp/Flex) expecting to retrieve data in parallel can fall into this trap easily.
Holding the session_write_close until after an expensive operation is likewise problematic.
To minimize effects, call session_write_close (aka session_commit) as early as practical (e.g. without introducing race conditions) or otherwise avoid the serialization bottleneck.
A simple session_start() will not be sufficiant to kepp you Session alive. 
Due to the filesystems mounting parameters, atime will normally not be updated. Instead of atime, mtime will be delivered.
This behavior may cause an early session death and your users my be kicked of your login system. 
To keep the session alive it will be necessary to write something into the sessionfile at each request, e. g. a simple 
 "$_SESSION['time'] = time();"
That would keep your session alive, even if the client in reality is only clicking around the site.
To avoid the notice commited by PHP since 4.3.3 when you start a session twice, check session_id() first:
if (session_id() == "")
 session_start();
The problem with SID is that if on occasions you don't start a session, instead of outputting an empty string for transparent integration it will return the regular undefined constant notice. So you might want to test the constant with defined() beforehand.
A note about session_start(), custom handlers and database foreign key constraints, which I think may be of some use...
We know that if we want our sessions into a database table (rather than the default storage), we can refer to session_set_save_handler(...) to get them there. Note that session_set_save_handler must (obviously) be called before session_start(), but let me get to the point...
Upon calling session_start() the "first time", when the session does not already exist, php will spawn a new session but will not call the write handler until script execution finishes.
Thus, the session at this point exists in the server process memory, but won't be visible as a row in the DB before the script ends.
This seems reasonable, because this avoids some unnecessary database access and resource usage before we even populate our session with meaningfull and definitive data, but this also has side-effects.
In my case, the script called session_start() to make sure a session was initiated, then used session_id() to populate another table in the DB, which had foreign_key constraint to the "sessions" table. This failed because no session was in the db at that point, yet!
I know I could simply force the creation of the row in the DB by manually calling the write handler after session_start(), when necessary, but I am not sure if this is the best possible approach.
As soon as I find an "elegant" solution, or a completely different approach, I will post some working sample code.
In the meanwhile... have fun!
The following code shows how the PHP session works. The function my_session_start() does almost the same thing as session_start().

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)