且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查用户是否已在php中登录?

更新时间:2023-09-10 20:07:34

登录不是太复杂,但是几乎所有登录过程都需要一些特定的部分.

Logins are not too complicated, but there are some specific pieces that almost all login processes need.

首先,确保将所有需要登录状态知识的页面都启用了会话变量,方法是将其放在这些页面的开头:

First, make sure you enable the session variable on all pages that require knowledge of logged-in status by putting this at the beginning of those pages:

session_start();

接下来,当用户通过登录表单提交其用户名和密码时,通常将通过查询包含用户名和密码信息的数据库(例如MySQL)来检查其用户名和密码.如果数据库返回匹配项,则可以设置一个会话变量以包含该事实.您可能还希望包括其他信息:

Next, when the user submits their username and password via the login form, you will typically check their username and password by querying a database containing username and password information, such as MySQL. If the database returns a match, you can then set a session variable to contain that fact. You might also want to include other information:

if (match_found_in_database()) {
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $username; // $username coming from the form, such as $_POST['username']
                                       // something like this is optional, of course
}

然后,在取决于登录状态的页面上,添加以下内容(请不要忘记session_start()):

Then, on the page that depends on logged-in status, put the following (don't forget the session_start()):

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
    echo "Please log in first to see this page.";
}

这些是基本组件.如果您需要有关SQL方面的帮助,可以在网上找到很多教程.

Those are the basic components. If you need help with the SQL aspect, there are tutorials-a-plenty around the net.