简体   繁体   English

PHP登录,存储会话变量

[英]PHP Login, Store Session Variables

Yo. 呦。 I'm trying to make a simple login system in PHP and my problem is this: I don't really understand sessions. 我正在尝试用PHP创建一个简单的登录系统,我的问题是这样的:我真的不理解会话。

Now, when I log a user in, I run session_register("user"); 现在,当我登录用户时,我运行session_register(“user”); but I don't really understand what I'm up to. 但我真的不明白我在做什么。 Does that session variable contain any identifiable information, so that I for example can get it out via $_SESSION["user"] or will I have to store the username in a separate variable? 该会话变量是否包含任何可识别的信息,因此我可以通过$ _SESSION [“user”]将其输出或者我是否必须将用户名存储在单独的变量中? Thanks. 谢谢。

Let me bring you up to speed. 让我带你快速。

Call the function session_start(); 调用函数session_start(); in the beginning of your script (so it's executed every page call). 在脚本的开头(所以每次调用都会执行)。

This makes sessions active/work for that page automagicly. 这使得会话自动生成/为该页面工作。

From that point on you can simply use the $_SESSION array to set values. 从那时起,您可以简单地使用$ _SESSION数组来设置值。

eg 例如

$_SESSION['hello'] = 'world';

The next time the page loads (other request), this wil work/happen: 下次页面加载(其他请求)时,这将工作/发生:

echo $_SESSION['hello'];  //Echo's 'world'

To simply destroy one variable, unset that one: 要简单地销毁一个变量,请取消设置:

unset($_SESSION['hello']);

To destroy the whole session (and alle the variables in it): 破坏整个会话(并在其中推断变量):

session_destroy();

This is all there is about the sessions basics. 这就是会议基础知识。

The session is able to store any information you might find useful, so putting information in is up to you. 会话能够存储您可能觉得有用的任何信息,因此信息的输入取决于您。 To try some things out, try the following and see for yourself: 要尝试一些事情,请尝试以下方法并亲眼看看:

<?php

    session_start();
    if(isset($_SESSION['foo']))
    {
        echo 'I found something in the session: ' . $_SESSION['foo'];
    }
    else
    {
        echo 'I found nothing, but I will store it now.';
        $_SESSION['foo'] = 'This was a triumph.';
    }

?>

Calling this site the first time should store the information, storing it the second time will print it out. 第一次调用此站点应该存储信息,第二次存储它将打印出来。

So yeah, you can basically put anything you like in the session, for instance a username. 所以,是的,您基本上可以在会话中放置任何您喜欢的内容,例如用户名。

Keep in mind, however, that the session dies as soon as the user closes his browser. 但请记住,一旦用户关闭浏览器,会话就会消失。

$_SESSION['user'] must be set to your user's name/id so that when you try to read it the next time, you'd be able to identify that user. $ _SESSION ['user']必须设置为您的用户名/ ID,以便下次尝试阅读时,您将能够识别该用户。 For example: 例如:

login: $_SESSION['user'] = some_user_id; login:$ _SESSION ['user'] = some_user_id;

user area: $user = $_SESSION['user']; 用户区:$ user = $ _SESSION ['user']; // extract the user from database, based on the $user variable // do something //根据$ user变量//从数据库中提取用户//执行某些操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM