php 如何检查用户是否在php中登录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1545357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a user is logged-in in php?
提问by Andrew
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.
我对 php 很陌生,我试图弄清楚如何使用会话来检查和查看用户是否登录到网站,以便他们有权访问特定页面。
Is this something that is complicated or is it because I am a noob that I can't figure it out?
这是复杂的事情还是因为我是菜鸟而无法弄清楚?
Thanks for the help!
谢谢您的帮助!
回答by Ben Torell
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();
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:
接下来,当用户通过登录表单提交他们的用户名和密码时,您通常会通过查询包含用户名和密码信息的数据库(例如 MySQL)来检查他们的用户名和密码。如果数据库返回匹配项,则可以设置会话变量以包含该事实。您可能还想包括其他信息:
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
}
Then, on the page that depends on logged-in status, put the following (don't forget the session_start()):
然后,在取决于登录状态的页面上,输入以下内容(不要忘记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.";
}
Those are the basic components. If you need help with the SQL aspect, there are tutorials-a-plenty around the net.
这些是基本组件。如果您需要 SQL 方面的帮助,网上有很多教程。
回答by Troy Benson
In Login.html:
在 Login.html 中:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
</head>
<body>
<section class="container">
<div class="login">
<h1>Login</h1>
<form method="post" action="login.php">
<p><input type="text" name="username" value="" placeholder="Username"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
</body>
</html>
In Login.php:
在 Login.php 中:
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1){
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
}
In Member.php:
在 Member.php 中:
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.";
}
In MYSQL:
在 MYSQL 中:
CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
In Register.html:
在 Register.html 中:
<html>
<head>
<title>Sign-Up</title>
</head>
<body id="body-color">
<div id="Sign-Up">
<fieldset style="width:30%"><legend>Registration Form</legend>
<table border="0">
<form method="POST" action="register.php">
<tr>
<td>UserName</td><td> <input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td><td> <input type="password" name="password"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</form>
</table>
</fieldset>
</div>
</body>
</html>
In Register.php:
在 Register.php 中:
<?php
define('DB_HOST', '');
define('DB_NAME', '');
define('DB_USER','');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$userName = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO members (username,password) VALUES ('$userName','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
else
{
echo "Unknown Error!"
}
回答by hiburn8
Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.
此页面上的几乎所有答案都依赖于检查会话变量是否存在以验证用户登录。这绝对没问题,但重要的是要考虑到,如果同一裸机上有多个虚拟主机/站点,PHP 会话状态不是您的应用程序所独有的。
If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.
如果您在 Web 服务器上有两个 PHP 应用程序,都使用名为“isLoggedIn”的会话变量中的布尔标志检查用户的登录状态,那么用户可以登录其中一个应用程序,然后无需凭据即可自动访问第二个应用程序。
I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.
我怀疑即使是商业共享托管的最恐龙也不会让虚拟主机以这种方式共享相同的 PHP 环境,这种情况可能会发生在多个客户的站点(不再),但在您自己的环境中需要考虑。
The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].
非常简单的解决方案是使用标识应用程序的会话变量而不是布尔标志。例如$SESSION["isLoggedInToExample.com"]。
Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.
资料来源:我是一名渗透测试员,对不应该做的事情有很多经验。
回答by Sampson
Any page you want to perform session-checks on needs to start with:
您想要对任何页面执行会话检查都需要从以下内容开始:
session_start();
From there, you check your session array for a variable indicating they are logged in:
从那里,您检查会话数组中的变量,表明它们已登录:
if (!$_SESSION["loggedIn"]) redirect_to_login();
Logging them in is nothing more than setting that value:
登录它们只不过是设置该值:
$_SESSION["loggedIn"] = true;
回答by moriarty5
else if (isset($_GET['actie']) && $_GET['actie']== "aanmelden"){
$username= $_POST['username'];
$password= md5($_POST['password']);
$query = "SELECT password FROM tbl WHERE username = '$username'";
$result= mysql_query($query);
$row= mysql_fetch_array($result);
if($password == $row['password']){
session_start();
$_SESSION['logged in'] = true;
echo "Logged in";
}
}
回答by Richard Kok
you may do a session and place it:
您可以进行会话并将其放置:
//start session
session_start();
//check do the person logged in
if($_SESSION['username']==NULL){
//haven't log in
echo "You haven't log in";
}else{
//Logged in
echo "Successfully log in!";
}
note:you must make a form which contain $_SESSION['username'] = $login_input_username;
注意:您必须制作一个包含 $_SESSION['username'] = $login_input_username;
回答by user3627194
See this script for register. Simple and very easy to understand.
请参阅此脚本以进行注册。简单易懂。
<?php
define('DB_HOST', 'Your Host[Could be localhost or also a website]');
define('DB_NAME', 'databasename');
define('DB_USERNAME', 'Username[In many cases root but some sites offer MySql Page where the username might be different]');
define('DB_PASSWORD', 'whatever you keep[if username is root then 99% password is blank]');
$link = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
if (!$link) {
die('Could not connect line 9');
}
$DB_SELECT = mysql_select_db(DB_NAME, $link);
if (!$DB_SELECT) {
die('Could not connect line 15');
}
$valueone = $_POST['name'];
$valuetwo = $_POST['last_name'];
$valuethree = $_POST['email'];
$valuefour = $_POST['password'];
$valuefive = $_POST['age'];
$sqlone = "INSERT INTO user (name, last_name, email, password, age) VALUES ('$valueone','$valuetwo','$valuethree','$valuefour','$valuefive')";
if (!mysql_query($sqlone)) {
die('Could not connect name line 33');
}
mysql_close();
?>
Make Sure you make all the Database stuff using phpMyAdmin. Its a very easy tool to work with. You can find it here: http://www.phpmyadmin.net/home_page/index.php
确保您使用 phpMyAdmin 制作所有数据库内容。它是一个非常容易使用的工具。你可以在这里找到它:http: //www.phpmyadmin.net/home_page/index.php
回答by Jeacovy Gayle
Need on all pages before you check for current sessions
在检查当前会话之前需要在所有页面上
session_start();
Check if $_SESSION["loggedIn"] (is not) true - If not, redirect them to login page.
检查是否$_SESSION["loggedIn"] (不是) true - 如果不是,则将它们重定向到登录页面。
if($_SESSION["loggedIn"] != true){
echo 'not logged in';
header("Location: login.php");
exit;
}
回答by sumit bagthariya
<?php
session_start();
if(!isset($_SESSION["login"]) && $SESSION["login"] =="OK")){
header("Location: index.php");
exit;
?>

