如何获取/设置 session_id() 还是应该自动生成?
我的应用程序中有一些基本的会话处理.在每个页面中,我都会检查用户是否已登录.如果是,则他们已被 $_SESSION['user_id']
标识,并且他们的登录/注销记录在 MySQL 表中.
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.
我还想根据唯一 ID 记录来宾(未登录)的访问.我假设一旦 session_start()
被调用,内部 session_id
就会自动生成,并且调用 session_id()
我可以检索它.但这只是给出了一个未定义的变量"错误,所以我想我必须手动设置它..?如果是这样,那么最好的方法是什么,使其成为唯一的 ID,或者通常的方法是什么?
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_id
is 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?
感谢您的帮助...
在 PHP 中有两种使用会话和会话 ID 的方法:
There are 2 ways to use sessions and session id's in PHP:
1 - 自动生成会话 ID 并获取它:
1 - Auto generate the session ID and get it:
session_start();
$id = session_id();
2 - 手动设置会话 ID,然后启动它:
2 - Set the session ID manually and then start it:
session_id( 'mySessionId' );
session_start();
如果您打算设置会话 ID,您必须在调用 session_start() 之前设置它;如果您打算生成一个随机的 session_id(或继续在前一个页面请求中已经开始的),然后获取该 id 用于其他地方,您必须调用 session_start()
之前尝试使用 session_id()
来检索会话 ID.
If you intend to set the session ID, you must set it before calling session_start();
If you intend to generate a random session_id (or continue one already started in a previous page request) and then get that id for use elsewhere, you must call session_start()
before attempting to use session_id()
to retrieve the session ID.