如何获取/设置session_id()还是应该自动生成? [英] How to get/set session_id() or should it be generated automatically?
问题描述
我的应用程序中有一些基本的会话处理.在每个页面中,我检查用户是否登录.如果已经登录,则已经由$_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中有2种使用会话和会话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(或继续在上一个页面请求中启动的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.
这篇关于如何获取/设置session_id()还是应该自动生成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!