php 如何获取/设置 session_id() 还是应该自动生成?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7068791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:57:08  来源:igfitidea点击:

How to get/set session_id() or should it be generated automatically?

phpsessionunique

提问by grai

I have some basic session handling in my application. In each page I check if the user is logged in. If they are then they're already identified by $_SESSION['user_id'], and their login/logout is recorded in a MySQL table.

我的应用程序中有一些基本的会话处理。在每个页面中,我都会检查用户是否已登录。如果是,则他们已被 标识$_SESSION['user_id'],并且他们的登录/注销记录在 MySQL 表中。

I would also like to record visits by guests (not logged in) based on a unique id. I had assumed that once session_start()is called that an internal session_idis automatically generated and that calling session_id()I could retrieve this. But this just gives an "undefined variable" error, so I guess I have to set it manually..? If so then what's the best way so that it will be a unique ID, or what is the usual method?

我还想根据唯一 ID 记录来宾(未登录)的访问。我曾假设一旦session_start()被调用,内部session_id会自动生成并且调用session_id()我可以检索它。但这只是给出了一个“未定义的变量”错误,所以我想我必须手动设置它..?如果是这样,那么最好的方法是什么,使其成为唯一的 ID,或者通常的方法是什么?

Thanks for any help...

谢谢你的帮助...

回答by Brian

There are 2 ways to use sessions and session id's in PHP:

在 PHP 中有两种使用会话和会话 ID 的方法:

1 - Auto generate the session ID and get it:

1 - 自动生成会话 ID 并获取它:

session_start();
$id = session_id();

2 - Set the session ID manually and then start it:

2 - 手动设置会话 ID,然后启动它:

session_id( 'mySessionId' );
session_start();

If you intend to setthe session ID, you must set it beforecalling session_start(); If you intend to generate a random session_id (or continue one already started in a previous page request) and then getthat id for use elsewhere, you must call session_start()beforeattempting to use session_id()to retrieve the session ID.

如果要设置会话ID,必须调用session_start()之前设置;如果您打算生成一个随机 session_id(或继续在前一个页面请求中已经开始的),然后获取该 id 以在其他地方使用,您必须session_start()尝试使用之前调用session_id()来检索会话 ID。

回答by genesis

Here you can see it works for me (session is started silently) : http://sandbox.phpcode.eu/g/f6b6b.php

在这里你可以看到它对我有用(会话是静默启动的):http: //sandbox.phpcode.eu/g/f6b6b.php

You forgot to start your session, probably

你忘记开始你的会话了,可能

回答by Nausik

Well, it may be a little bit strange, but when I need unique ID I use uniqid()

好吧,这可能有点奇怪,但是当我需要唯一 ID 时,我使用 uniqid()