我对 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?
发布评论