如何获取/设置 session_id() 还是应该自动生成?
我的应用程序中有一些基本的会话处理。在每个页面中,我检查用户是否已登录。如果是,则他们已由 $_SESSION['user_id']
识别,并且他们的登录/注销记录在 MySQL 表中。
我还想根据唯一的 ID 记录客人的访问(未登录)。 我假设一旦调用 session_start()
,就会自动生成内部 session_id
并且调用 session_id()
我可以检索它。但这只会给出“未定义的变量”错误,所以我想我必须手动设置它..?如果是这样,那么使它成为唯一 ID 的最佳方法是什么,或者通常的方法是什么?
感谢您的帮助...
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.
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?
Thanks for any help...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 PHP 中使用会话和会话 ID 有 2 种方法:
1 - 自动生成会话 ID 并获取它:
2 - 手动设置会话 ID,然后启动它:
如果您打算设置会话ID,您必须在调用 session_start() 之前设置它;
如果您打算生成随机 session_id(或继续在上一页请求中已启动的会话),然后获取该 id 以供其他地方使用,则必须调用
session_start()
<尝试使用session_id()
检索会话 ID 之前。There are 2 ways to use sessions and session id's in PHP:
1 - Auto generate the session ID and get it:
2 - Set the session ID manually and then start it:
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 usesession_id()
to retrieve the session ID.在这里您可以看到它对我有用(会话以静默方式启动):http://sandbox.phpcode。 eu/g/f6b6b.php
您可能忘记开始会话
Here you can see it works for me (session is started silently) : http://sandbox.phpcode.eu/g/f6b6b.php
You forgot to start your session, probably
嗯,这可能有点奇怪,但是当我需要唯一 ID 时,我使用 uniqid()
Well, it may be a little bit strange, but when I need unique ID I use uniqid()