如何检查用户是否已在php中登录? [英] How to check if a user is logged-in in php?
问题描述
我对php还是很陌生,我试图弄清楚如何使用会话来检查并查看用户是否登录到网站,以便他们有权访问特定页面.
I'm pretty new to php and I am trying to figure out how to use sessions to check and see if a user is logged into a website so that they would have authorization to access specific pages.
这是复杂的事情,还是因为我是菜鸟而无法解决?
Is this something that is complicated or is it because I am a noob that I can't figure it out?
感谢您的帮助!
推荐答案
登录不是太复杂,但是几乎所有登录过程都需要一些特定的部分.
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.
这篇关于如何检查用户是否已在php中登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!